containers
docker exec
Runs a new command inside an already running container. Commonly used for shells, debugging, or one-off maintenance tasks.
docker exec [OPTIONS] CONTAINER COMMAND [ARG...] Common flags
| Flag | Purpose |
|---|---|
| -i, --interactive | Keep STDIN open even if not attached |
| -t, --tty | Allocate a pseudo-TTY |
| -d, --detach | Run the command in the background |
| -e, --env | Set environment variables for the exec session |
| -u, --user | Run as a specific user (name or UID) |
| -w, --workdir | Working directory inside the container |
Examples
docker exec -it web sh Open an interactive shell in the 'web' container
docker exec -u root api apt-get update Run a command as root regardless of the image USER
docker exec db psql -U postgres -c 'SELECT version();' One-shot SQL query
docker exec -d worker /usr/local/bin/warmup.sh Fire-and-forget background task
Gotcha
Container must be running — exec fails on stopped containers. Environment variables set at run time are inherited, but PATH may differ if the target binary isn't absolute.
Related commands
docker run
Creates and starts a new container from a specified image in a single step. This is the primary command for launching workloads and supports extensive configuration for networking, storage, and process control.
docker logs
Fetches the stdout/stderr logs of a container. Works with the json-file and local logging drivers; other drivers require querying the destination directly.
docker ps
Lists containers along with their status, ports, and identifiers. By default it shows only running containers unless -a is passed.
docker inspect
Returns low-level JSON metadata about Docker objects — containers, images, networks, volumes, and more. Supports Go template formatting for extracting specific fields.
docker stop
Gracefully stops one or more running containers by sending SIGTERM and then SIGKILL after a timeout. Use docker kill for an immediate SIGKILL.
← All Docker commands · Docker vs Kubernetes · Docker vs VMs