I have a microservice running in a Docker container, and I need to inspect the logs and check the internal configuration files without restarting or stopping the container. Is there a way to open an interactive shell session inside the already running container? I am worried that if I use a standard start command, it might interfere with the production traffic currently being handled by the app. What is the safest syntax to use for this kind of live debugging in a DevOps environment?
3 answers
The standard tool for this is the docker exec command. Unlike docker run, which creates a brand new container, exec creates a new process within an existing one. To get a full interactive bash terminal, you should use the command: docker exec -it <container_id> /bin/bash. The -i stands for interactive and -t allocates a pseudo-TTY, which makes it feel like a real terminal session. This is incredibly safe for production environments because it doesn't restart your entrypoint process, meaning your application continues to serve users while you are poking around inside the file system to troubleshoot issues.
Is there a difference in how this works if the container was started using Docker Compose instead of a direct docker run command? I’ve tried using docker-compose exec, but sometimes it tells me the service is not running even when the container clearly is—does the service name replace the ID in that specific context?
You can also run single commands without entering a shell. For example, docker exec <id> ls /app will list the files and immediately exit back to your local terminal.
That is a great tip, Amanda! I find it much faster for quick checks. It’s a very efficient way to verify file permissions without the overhead of maintaining an interactive session.
Robert, you're exactly right! When using Docker Compose, you must use the service name defined in your YAML file rather than the specific container ID. The great thing about docker-compose exec is that it automatically finds the correct container instance for you. Also, keep in mind that if your container is based on a slim image like Alpine, /bin/bash might not exist. In those cases, you’ll need to use /bin/sh instead. I always try sh first if bash throws a "file not found" error during a live cloud deployment.