Docker Compose — Startup & Shutdown Order
Understanding the full lifecycle — startup, running, and graceful shutdown — helps you build reliable Compose stacks.
Startup Order
Compose resolves dependencies into a DAG (Directed Acyclic Graph):
┌─── cache
web ── api ─┤
└─── db ── migrate (completed_successfully)
Parallel where possible: cache and db start simultaneously.
Shutdown Order
Shutdown is the reverse of startup:
Startup: migrate → db + cache → api → web
Shutdown: web → api → cache + db → migrate (already exited)
Graceful Shutdown
Docker sends SIGTERM to PID 1, then waits for stop_grace_period:
services:
api:
image: node:20-alpine
stop_grace_period: 30s # Default: 10s
stop_signal: SIGTERM # Default: SIGTERM
After the grace period, Docker sends SIGKILL.
Stop Grace Period
| Scenario | Recommended |
|---|---|
| Stateless API | 10s (default) |
| Database | 30-60s |
| Queue worker | 60-120s |
| Background jobs | Match max job duration |
Handling SIGTERM in Your App
Node.js:
process.on('SIGTERM', async () => {
console.log('Shutting down gracefully...');
await server.close();
await db.disconnect();
process.exit(0);
});
Python:
import signal, sys
def shutdown(signum, frame):
print("Shutting down gracefully...")
# Close connections, flush buffers
sys.exit(0)
signal.signal(signal.SIGTERM, shutdown)
Complete Lifecycle Example
services:
web:
image: nginx:alpine
depends_on:
api:
condition: service_healthy
stop_grace_period: 5s
api:
image: myapi:latest
healthcheck:
test: ["CMD-SHELL", "curl -f http://localhost:3000/health || exit 1"]
interval: 10s
timeout: 5s
retries: 3
depends_on:
db:
condition: service_healthy
stop_grace_period: 30s
db:
image: postgres:16
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 5s
timeout: 3s
retries: 5
start_period: 10s
stop_grace_period: 60s
Summary
| Phase | Behavior |
|---|---|
| Startup | Follow depends_on + conditions |
| Running | Health checks monitor status |
| Shutdown | Reverse order, SIGTERM + grace |
| Force kill | SIGKILL after grace period |
Quick Reference
| Item | Detail |
|---|---|
| Startup | Follows depends_on DAG |
| Shutdown | Reverse of startup |
| SIGTERM | Sent first for graceful stop |
| stop_grace_period | Time before SIGKILL (default 10s) |
| SIGKILL | Forced after grace period |