✦ For everyone, free.

Practical knowledge for real and everyday life

Home

9.4.4 Compose Exec

A focused guide to Compose Exec, connecting core concepts with practical Docker and container operations.

docker compose exec runs a command inside an already-running service's container, providing interactive or one-off access to that container's environment, exactly as docker exec would for an individually managed container, but referencing the service by its Compose-defined name.

Running a Command Inside a Running Service

The basic form names the service and the command to execute within it.

docker compose exec api sh

This opens an interactive shell session inside the running api service's container.

Running a Specific, Non-Interactive Command

Beyond an interactive shell, any specific command can be executed, with its output returned directly.

docker compose exec db psql -U postgres -c "SELECT version();"
Why Exec Requires an Already-Running Service

Unlike run, which starts a brand-new container for a one-off task, exec specifically operates against a service that's already running — attempting to exec into a service that isn't currently up results in an error.

docker compose exec api ls /app
ERROR: Service "api" is not running.
Specifying Which Container When a Service Has Multiple Replicas

For a scaled service running several replicas, exec defaults to the first one unless a specific instance is explicitly selected.

docker compose exec --index=2 api sh
A Common Use Case: Inspecting or Debugging a Running Service

Checking a running service's actual filesystem state, environment variables, or running processes directly is a common, practical use of exec.

docker compose exec api env
docker compose exec api ps aux
Why Compose Exec Matters

exec provides essential direct access into an already-running service's container, valuable for interactive debugging, running administrative commands, and verifying a service's actual internal state without needing to stop or recreate it.

Content in this section