docker exec starts an extra process in a running container. It uses the container's filesystem, environment and network.
text
container web
├── PID 1 nginx (main process: decides when the container stops)
└── PID n cat /etc/os-release ◄── docker exec web cat /etc/os-releaseOne-off commands
sh
docker exec web cat /etc/os-releasetext
PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
HOME_URL="https://www.debian.org/"The output comes back to your terminal and the command returns.
| Command | Use |
|---|---|
docker exec web ls /usr/share/nginx/html | look at files |
docker exec web env | see the process environment |
docker exec web curl -s localhost | test the server from inside the container |
docker exec -w /etc/nginx web ls | run in a different working directory |
Commands with pipes or redirects
Your host shell processes > and | before Docker sees them. To redirect inside the container, run a shell there:
sh
docker exec web sh -c 'echo ok > /usr/share/nginx/html/health.txt'
docker exec web curl -s localhost/health.txttext
okWithout sh -c, the > would write a file on the host.
Interactive shell
sh
docker exec -it web bashtext
root@e1dd94dc29ef:/# cd /usr/share/nginx/html
root@e1dd94dc29ef:/usr/share/nginx/html# ls
50x.html
health.txt
index.html
root@e1dd94dc29ef:/usr/share/nginx/html# exit| Flag | Meaning |
|---|---|
-i | keep stdin open so the shell reads what you type |
-t | allocate a terminal (prompt, line editing) |
The prompt shows root@<short container ID>. exit ends the shell. The container keeps running.
| Image | Shell to use |
|---|---|
Debian-based (nginx, redis, postgres, node, python) | bash |
| Alpine, BusyBox | sh (no bash) |
Limits
- The container must be running:
text
Error response from daemon: container e1dd94dc29ef... is not running- Only programs in the image exist. nginx has no
ps:
text
OCI runtime exec failed: exec failed: unable to start container process: exec: "ps": executable file not found in $PATH: unknown- Changes are made in the container's writable layer. They survive stop and start, and disappear when the container is removed. The image does not change.