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

← All Docker commands · Docker vs Kubernetes · Docker vs VMs