Lesson 20: Managing the Compose Lifecycle (Stop, Down, Restart)
Knowing how to gracefully shut down and clean up your stack is essential.
1. Stopping Services
Use docker compose stop to stop the containers gracefully without removing them. They can be restarted later very quickly.
bash docker compose stop
To restart stopped services:
bash docker compose start
2. Removing the Stack (docker compose down)
The down command stops containers and removes the containers and default networks created by compose up.
bash docker compose down
Cleaning Up Everything (Including Volumes)
Crucially, down does not remove persistent volumes by default, as that would delete your data (e.g., the PostgreSQL data).
To remove containers, networks, and also named volumes (use with caution):
bash docker compose down -v
3. Rebuilding Images
If you change your application code or modify the Dockerfile, you need to rebuild the image before the containers use the new version.
To stop, rebuild, and restart the stack:
bash docker compose up --build -d
4. Executing Commands inside a Running Service
To run an interactive command (like a shell or migration script) inside a running container, use docker compose exec:
bash
Open a shell inside the running web container
docker compose exec web sh
Run a database migration script
docker compose exec db psql -U user -d mydb
docker compose exec is equivalent to docker exec but uses the service name defined in your compose.yml.