How to Use Docker Compose Exec: Simple Guide
Use
docker compose exec [service] [command] to run a command inside a running container of a service defined in your Compose file. This lets you interact with the container without opening a new terminal or restarting it.Syntax
The basic syntax of docker compose exec is:
docker compose exec: The command to execute a command inside a running container managed by Docker Compose.[service]: The name of the service as defined in yourdocker-compose.ymlfile.[command]: The command you want to run inside the container.
bash
docker compose exec [service] [command]
Example
This example shows how to run an interactive shell inside a running web service container using docker compose exec. It lets you explore the container's file system or run commands directly.
bash
version: '3.8' services: web: image: nginx:alpine ports: - "8080:80" # After starting the service with: # docker compose up -d # Run an interactive shell inside the 'web' container: docker compose exec -it web sh
Output
# You will see a shell prompt inside the container, e.g.:
/ # ls
bin dev etc home lib media mnt proc root run sbin srv sys tmp usr var
Common Pitfalls
Common mistakes when using docker compose exec include:
- Trying to run
execon a service that is not running. The container must be up. - Forgetting to use an interactive terminal with
-itwhen running shells or interactive commands. - Confusing
docker compose execwithdocker compose run, which starts a new container instead of using an existing one.
bash
docker compose exec web sh # May fail if the container is not running docker compose exec -it web sh # Correct way to get an interactive shell docker compose run web sh # Starts a new container, not the running one
Quick Reference
Here is a quick cheat sheet for docker compose exec usage:
| Command | Description |
|---|---|
| docker compose exec web ls /app | Run ls /app inside the web container |
| docker compose exec -it db psql | Open interactive PostgreSQL shell inside db container |
| docker compose exec api curl http://localhost | Run curl inside api container |
| docker compose exec -it web sh | Run shell inside web container (interactive) |
| docker compose exec -u root web sh | Run shell as root user inside web container |
Key Takeaways
Use
docker compose exec [service] [command] to run commands inside running containers.Add
-it flags for interactive commands like shells.The service container must be running before using
exec.Do not confuse
exec with run; exec uses existing containers.You can specify user with
-u to run commands as different users.