docker exec
Run a command in a running container. Useful for debugging, shell access, or one-off tasks.
Syntax
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
Examples
Example 1
docker exec -it my-container bash
Open interactive bash shell in the container.
Example 2
docker exec my-container ls /app
Run a one-off command (list files).
Example 3
docker exec my-container env
View environment variables inside the container.
Common flags
| Flag | Description |
|---|---|
| -d, --detach | Run in background |
| -it | Interactive TTY |
| -e, --env | Set environment variable |
| -w, --workdir | Working directory inside container |
Tips & best practices
- •Use -it for interactive shells (bash, sh).
- •exec runs in the container's filesystem; changes persist until container restarts.