Executing Commands (exec)
docker exec runs a command inside an already-running container, letting you open a shell to inspect it.
docker exec [options] CONTAINER commandSometimes you need to look inside a running container — check a config file, view a log, or debug a problem. The docker exec command runs a new command in an existing container.
Opening a shell
The most common use is starting an interactive shell with -it. Many small images only include sh rather than bash.
Running one-off commands
You can also run a single command without an interactive session, for example listing files or printing an environment variable.
Example
# Open an interactive shell in a running container
docker exec -it web sh
# Run a single command without a shell session
docker exec web ls /usr/share/nginx/html
# Check an environment variable inside the container
docker exec web printenv PATHWhen to use it
- A developer opens a shell inside a running container to manually inspect config files and running processes while debugging.
- An ops engineer runs a one-off database migration script inside an already-running application container.
- A QA tester uses docker exec to tail a log file inside a container when the application log is not forwarded to stdout.
More examples
Open interactive shell in container
Opens an interactive shell session inside an already-running container for manual inspection.
docker exec -it myapp bash
# Or with Alpine-based images that lack bash:
docker exec -it myapp shRun a one-off command
Executes non-interactive commands inside the container to inspect state without opening a full shell.
# List processes inside the container
docker exec myapp ps aux
# Check a config file
docker exec myapp cat /etc/nginx/nginx.confRun command as specific user
Uses --user to run the command as a non-root user inside the container for safer privileged operations.
# Run migration as the app user, not root
docker exec -it --user appuser myapp node scripts/migrate.js
Discussion