Docker Compose: Orchestrating Multi-Container Applications
Define and run multi-container Docker applications using Docker Compose. From local development environments to complex microservice topologies.
Docker Compose defines and runs related containers from a Compose file. This guide covers service configuration, networking, health checks, secrets, and local workflows, with notes on where single-host Compose ends and cluster orchestration begins.
Docker Compose: Orchestrating Multi-Container Applications
Docker Compose reads a YAML file and creates the services, networks, and volumes for an application. Use the current CLI form, docker compose, to validate and run that configuration.
This guide focuses on local development, CI, and workloads on one Docker Engine. Compose does not schedule services across a multi-host cluster; use an orchestrator such as Docker Swarm or Kubernetes when workloads must span hosts.
The examples follow the rolling Compose Specification and target Docker Compose v5.7.1. The top-level version field is obsolete; current Compose ignores it. See the Compose version reference and release notes.
When to Use Docker Compose
Compose is a practical fit when one machine or CI runner can host the stack. It also works for some single-host deployments, provided you handle backups, updates, and recovery for that host.
Use Docker Compose when:
- Local development — spinning up the full stack on your machine with hot reload and debugging
- CI/CD testing — running integration tests in isolated containers without external dependencies
- Single-host deployment — deploying a complete stack to a single VM or dedicated server
- Prototyping — rapidly iterating on architecture without infrastructure complexity
- Services that can run on one Docker Engine and use straightforward networking
Consider a cluster orchestrator when:
- Horizontal scaling limits —
docker compose up –scaledoes not provide automatic load balancing or self-healing - Multi-host scheduling — Compose does not distribute services across Docker Engines
- Rolling updates — manual image updates with downtime or complex blue-green scripts
- Service discovery at scale — DNS-based discovery works for handfuls of services, not hundreds
- Resource isolation — no built-in CPU/memory limits across the entire stack, only per-container
Choose an orchestrator based on the deployment environment:
- Multiple nodes required — workloads exceed what a single host can handle or you need high availability
- Enterprise compliance — role-based access control, network policies, and audit logs are requirements
- Complex CI/CD pipelines — automated rollouts, rollbacks, and canary deployments are daily operations
- Service mesh needs — traffic management, circuit breaking, and observability beyond basic health checks
- Multi-environment consistency — same manifests across dev, staging, production with different configurations
Compose File Structure
A Compose file, commonly named compose.yaml, describes the application stack:
services:
web:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
depends_on:
- db
- redis
db:
image: postgres:15-alpine
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
POSTGRES_DB: app
POSTGRES_USER: user
POSTGRES_PASSWORD: secret
redis:
image: redis:7-alpine
volumes:
- redis_data:/data
volumes:
postgres_data:
redis_data:
networks:
default:
driver: bridge
The Compose Specification evolves independently of a file-format number. Current Compose implementations ignore the obsolete top-level version field; omit it in new files.
Service Dependency Topology
The example stack from the YAML above has the following dependency graph:
graph LR
User([Browser]) --> Web[Web Service<br/>:3000]
Web --> API[API Service<br/>:4000]
API --> DB[(PostgreSQL<br/>:5432)]
API --> Redis[(Redis<br/>:6379)]
Each arrow represents a network connection. Docker Compose automatically creates a shared bridge network where services can reach each other by service name.
Service Definitions and Dependencies
Each entry under services is a container. Docker Compose builds or pulls the image, then starts the container with the specified configuration.
Building from Dockerfile
services:
web:
build:
context: .
dockerfile: Dockerfile
args:
NODE_ENV: production
image: myapp:latest
The build instruction tells Compose to build the image from a Dockerfile. The image instruction names the resulting image. If you omit image, Compose names it projectname_web.
Using Pre-Built Images
services:
db:
image: postgres:15-alpine
Docker pulls the image if not present locally.
depends_on
Short-form depends_on controls startup order, but it does not wait for a dependency to become ready:
services:
web:
build: .
depends_on:
- db
- redis
api:
build: ./api
depends_on:
- db
db:
image: postgres:15-alpine
Compose starts db first, then web and api in parallel. The directive does not wait for the database to be ready, only for the container to start. For databases and similar services, implement application-level retry logic or use healthcheck with condition.
Health Checks and Conditions
services:
db:
image: postgres:15-alpine
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d app"]
interval: 5s
timeout: 3s
retries: 5
web:
build: .
depends_on:
db:
condition: service_healthy
With the long form and a health check, Compose waits until db reports healthy before starting web. This is a startup gate; the application should still handle later database disconnects.
Networking with Compose
Compose creates a default network for your stack. All services join this network and can reach each other by service name.
Automatic DNS Resolution
services:
web:
build: .
environment:
- DATABASE_URL=postgres://db:5432/app
db:
image: postgres:15-alpine
The web service can reach db at postgres://db:5432/app. Docker embedded a DNS resolver that resolves service names to container IPs.
Custom Networks
For more control, define explicit networks:
services:
frontend:
build: ./frontend
networks:
- frontend_net
backend:
build: ./backend
networks:
- frontend_net
- backend_net
db:
image: postgres:15-alpine
networks:
- backend_net
networks:
frontend_net:
driver: bridge
backend_net:
driver: bridge
The frontend can reach the backend, and the backend can reach the database. The frontend cannot reach the database directly. This segmentation adds security.
External Networks
Use an existing Docker network instead of letting Compose create a new one. This matters when your stack needs to coexist with other containers on the same host — for example, connecting to a database container that was started separately, or integrating with a monitoring stack that runs outside Compose management.
networks:
default:
external: true
name: my_pre-existing_network
The external: true flag tells Compose to leave this network alone — it will not create or destroy it. Compose assumes the network already exists and fails if it does not. If your network uses a custom driver or lives in a different Docker context, specify the driver explicitly with driver: bridge. Run docker network ls to check what networks are available on the host before running docker compose up.
Environment Variables and Secrets
Compose provides several ways to inject configuration into services.
Basic Environment Variables
Use the environment block to set variables directly in the compose file. This works well for non-sensitive configuration that varies between environments — development flags, feature toggles, endpoint URLs.
services:
web:
environment:
- NODE_ENV=production
- API_KEY=secret123
- DEBUG=false
Inline environment variables show up in docker compose ps output and in the container’s environment list. Only use this for non-sensitive config. If you are putting real passwords in here, switch to the .env approach below or Docker secrets for Swarm deployments.
Environment from .env File
Create a .env file in the same directory as docker-compose.yml:
NODE_ENV=production
API_KEY=secret123
DATABASE_URL=postgres://user:pass@db:5432/app
Reference variables in docker-compose.yml:
services:
web:
environment:
- NODE_ENV=${NODE_ENV}
- API_KEY=${API_KEY}
- DATABASE_URL=${DATABASE_URL}
Compose secrets and Swarm secrets
Compose can mount a declared secret into only the services that need it. For local Compose, a file-backed secret remains a file on the host; Compose does not turn it into a managed, encrypted secret store. Restrict the source file’s permissions, keep it out of version control, and use a production secret manager when your deployment needs centralized access control, rotation, or audit history.
services:
db:
image: postgres:15-alpine
secrets:
- db_password
environment:
POSTGRES_PASSWORD_FILE: /run/secrets/db_password
secrets:
db_password:
file: ./secrets/db-password.txt
For a Swarm service, Docker manages secrets through the Swarm control plane and mounts them at runtime. See the Compose secrets reference and Swarm secrets guide; the two deployment modes have different storage and lifecycle guarantees.
Handling credentials
Do not place real credentials in a committed Compose file, .env file, image, or logs. Keep local secret files ignored by Git and rotate any credential that has already been pushed. In CI, use the platform’s secret store and pass each value only to the job or service that needs it. For production, select a secret manager that meets the deployment’s access, rotation, and audit requirements.
Development vs Production Workflows
Compose files often differ between development and production.
Development Compose File
# docker-compose.yml
services:
web:
build: .
volumes:
- ./src:/app/src:ro # Hot reload
environment:
- NODE_ENV=development
ports:
- "3000:3000"
- "9229:9229" # Debug port
Mounting source code as a volume enables hot reload. Changes on your host appear immediately inside the container.
Production Compose File
# docker-compose.prod.yml
services:
web:
build:
context: .
dockerfile: Dockerfile.prod
environment:
- NODE_ENV=production
ports:
- "3000:3000"
restart: unless-stopped
healthcheck:
test:
[
"CMD",
"wget",
"--no-verbose",
"--tries=1",
"--spider",
"http://localhost:3000/health",
]
interval: 30s
timeout: 3s
retries: 3
start_period: 10s
No volumes for source code (code is baked into the image). Explicit health checks. Restart policy.
Using Multiple Compose Files
# Start with both files (base + override)
docker compose up -d
# Use production file instead of development
docker compose -f docker-compose.yml -f docker-compose.prod.yml up -d
The prod file overrides settings from the base file. Build context, environment variables, and volumes get replaced.
Scaling Services
Compose can run multiple replicas of a service:
docker compose up -d --scale web=3
This runs 3 instances of the web service. However, port mapping becomes tricky with multiple replicas since you cannot map the same host port to multiple containers.
Scaling with a Load Balancer
For actual load balancing, use a tool like nginx or Traefik in front of your scaled services:
services:
web:
build: .
scale: 3
nginx:
image: nginx:alpine
ports:
- "80:80"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
depends_on:
- web
Each web container gets a unique name (web_1, web_2, web_3). Configure nginx to balance across web_1, web_2, web_3.
Comparison: Docker Compose vs Kubernetes
Compose and Kubernetes take different approaches to the same problem. Compose runs containers on a single host using a declarative YAML file. Kubernetes distributes workloads across a cluster, scheduling pods, handling service discovery, and managing rolling updates automatically. The table below breaks down the operational differences that matter most in practice.
| Operational concern | Docker Compose | Kubernetes |
|---|---|---|
| Scaling | Manual with –scale, no built-in load balancer |
HorizontalPodAutoscaler with automatic load distribution |
| Service discovery | DNS on a bridge network, limited to the single host | DNS via Services with built-in retry and failover |
| Update strategy | Manual or scripted blue-green deployments | RollingUpdate and Recreate strategies built in |
| Self-healing | Container restart on failure | Pod rescheduling, node replacement, quorum-based controllers |
| Secret management | Compose secret mounts; use Swarm or an external manager when its lifecycle guarantees are needed | Kubernetes Secrets (encrypt at rest only when configured) |
| Network policies | Manual network segmentation | NetworkPolicy CRD for fine-grained L3/L4 rules |
| Storage | Named volumes and bind mounts | PersistentVolumeClaim with dynamic provisioning |
For a team of five running a twelve-service stack on a single VM, Compose wins on simplicity. One file, one command, stack is up. The operational surface is small enough that manual intervention handles most failure scenarios. When that same team grows to twenty engineers and the stack sprawls across forty services needing multi-node placement, the gaps become painful. Kubernetes earns its complexity at that scale — autoscaling, rolling updates, and self-healing replace scripts you would otherwise build and maintain by hand. The migration is not trivial. Concepts translate but manifests, ingress controllers, and cluster provisioning are all new surface area. Start evaluating Kubernetes when the operational cost of Compose scripting exceeds the learning investment.
Common Commands
Starting Your Stack
# Start all services
docker compose up -d
# Start and rebuild if images are outdated
docker compose up -d --build
# Start specific services
docker compose up -d web db
# Start with override file
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d
Viewing Logs
# Follow logs from all services
docker compose logs -f
# Follow logs from specific service
docker compose logs -f web
# Tail logs with timestamps
docker compose logs -f --tail=100 --timestamps web
Checking Status
# List running services
docker compose ps
# List images used by services
docker-compose images
# Inspect service configuration
docker compose config
Stopping and Cleaning Up
# Stop services (containers remain)
docker compose stop
# Stop and remove containers
docker compose down
# Stop and remove containers and volumes
docker compose down -v
# Stop and remove everything including images
docker compose down --rmi local
Executing Commands in Services
# Run a command in a service
docker compose exec web node --version
# Run with interactive shell
docker compose exec web sh
# Run database migrations
docker compose exec api npm run migrate
Building Multi-Architecture Images
For services that need to run on different architectures:
services:
web:
build:
context: .
dockerfile: Dockerfile
platforms:
- linux/amd64
- linux/arm64
Use Docker buildx for the actual build:
docker buildx bake -f docker-compose.yml
docker buildx push --platforms linux/amd64,linux/arm64 myapp:latest
Extending Compose Files
Compose supports extending services from other files:
# docker-compose.yml (base)
services:
web:
build: .
environment:
- NODE_ENV=${NODE_ENV}
# docker-compose.dev.yml (extends base)
services:
web:
volumes:
- ./src:/app/src:ro
ports:
- "3000:3000"
Run with:
docker compose -f docker-compose.yml -f docker-compose.dev.yml up -d
The dev file adds volumes and ports to the base service without duplicating the build configuration.
Troubleshooting
Service Fails to Start
# Check logs first
docker compose logs web
# Verify service configuration
docker compose config
# Recreate containers
docker compose up -d --force-recreate
Port Conflicts
When two services try to bind the same host port, one container fails to start. This commonly happens when you have multiple Compose stacks on the same host, or when a service accidentally maps to a port already used by another process.
Diagnose the conflict:
# Check what is using the port
ss -tlnp | grep 3000
# Find containers using the port across all Compose projects
docker compose ps -a | grep 3000
# List all containers to find leftover stacks
docker ps -a --format "{{.Names}}\t{{.Ports}}"
Resolve the conflict:
Change the host port in your compose file. Use a high port range (30000-32767) for development to avoid clashing with well-known ports. If the conflicting container is from another Compose stack, bring it down first: docker compose -f /path/to/project/docker-compose.yml down. If the port is held by a system service, either stop the service or map your container to a different port.
Prevent future conflicts:
Use docker compose ps before starting a new stack to see what ports are already in use. In shared development environments, assign each developer a port range via an override file. Avoid mapping to ports below 1024 — these are reserved for system services on most systems.
Volume Permission Issues
Containers often run as non-root. If your application cannot read a mounted volume:
# Check current ownership
ls -la ./data
# Fix ownership in a temporary container
docker compose run --rm alpine chown -R 1001:1001 /data
DNS Resolution Failures
# Check if container can resolve names
docker compose exec web ping api
# Check DNS configuration
docker compose exec web cat /etc/resolv.conf
# Restart the network
docker compose down
docker compose up -d
Production Failure Scenarios
Compose stacks fail in ways that are not always obvious. Here are the most common issues.
Volume Permission Issues After Image Update
When you update an image, the UID/GID the container runs as may change. If the volume has data owned by the old UID, the new container cannot read or write.
Symptoms: “Permission denied” errors immediately after docker compose pull.
Diagnosis:
# Check container user
docker compose exec web id
# Check volume ownership
ls -la ./data
Mitigation: Always test image updates in staging. Use a named volume instead of a bind mount for application data so ownership is managed by Docker.
Circular Dependency Deadlock
If service A depends on B and B depends on A, Compose may hang at startup.
Symptoms: docker compose up hangs, services never start, logs show services waiting on each other.
Diagnosis:
# Check your depends_on configuration
docker compose config | grep -A5 depends_on
Mitigation: Review depends_on configuration. Use condition: service_healthy with health checks instead of simple dependency ordering.
Secrets File Missing on First Start
If a service requires a secret file that does not exist when Compose starts, the service fails.
Symptoms: ERROR: file not found at startup, even though the file was supposed to be created by another service.
Diagnosis:
# Check if secret file exists
ls -la ./secrets/db-password.txt
Mitigation: Use docker compose up –exit-code-from to capture failures, or add a startup health check that validates dependencies exist before starting dependent services.
Capacity Estimation
How many containers can a single host support? This depends on CPU, memory, and network capacity, not just Docker.
Rough guidelines for a typical host (4 cores, 8GB RAM):
| Container Type | Containers per Host |
|---|---|
| Lightweight (nginx, redis) | 50-100 |
| Medium (Node.js, Python) | 10-30 |
| Heavy (JVM, databases) | 3-8 |
These are soft limits. The real constraint is your application resource usage. Monitor actual consumption with docker stats.
Memory estimation:
# Check container memory usage
docker stats --no-stream
# Each Node.js container ~100-300MB
# Each Python worker ~200-500MB
# Each PostgreSQL ~500MB-2GB
Observability
Logging Configuration
Configure Compose to send logs to a centralized system:
services:
web:
image: myapp:latest
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "3"
For production, use the syslog or fluentd logging driver to send logs to a central log aggregator.
Centralized Logging Example
services:
web:
image: myapp:latest
logging:
driver: fluentd
options:
fluentd-address: localhost:24224
tag: web
Health Checks for Services
Add health checks to ensure services are genuinely ready:
services:
api:
image: myapi:latest
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 3s
retries: 3
start_period: 10s
Use condition: service_healthy in depends_on to ensure services only start after their dependencies are genuinely ready.
Security Checklist
Use this checklist when deploying Docker Compose to production:
- Keep credentials out of committed Compose files; use local secret files for development and a suitable secret manager in production
- Use specific image tags, not
latest— pins versions for reproducibility - Scan images for vulnerabilities before deployment (
trivy image) - Run services as non-root user (
user: “1001:1001”) - Use read-only root filesystems where possible (
read_only: true) - Limit container capabilities (
cap_drop: ALL) - Separate services by trust boundary — do not put untrusted services in the same Compose stack
- Rotate secrets regularly — implement secret rotation procedures
- Use TLS for any internal service-to-service communication
- Set resource limits (memory, CPU) to prevent one service from starving others
Trade-off Analysis
Tool Selection Criteria
| Factor | Docker Compose | Kubernetes |
|---|---|---|
| Scope | Single host | Multi-node cluster |
| Scaling | Manual (–scale), no auto-balancing |
HorizontalPodAutoscaler with auto-balancing |
| Service discovery | DNS via bridge network | DNS via Services with multiple discovery options |
| Rolling updates | Manual with downtime or blue-green | Built-in with zero-downtime via Deployment |
| Self-healing | Container restart only | Automatic pod rescheduling, node replacement |
| Secrets | Compose file secret mounts (Swarm manages them separately) | Kubernetes Secrets (encryption at rest must be configured) |
| Load balancing | Manual (nginx sidecar) | Built-in via Service type LoadBalancer |
| Learning curve | Gentle | Steeper |
| Complexity | Low (single file) | High (YAML, Helm, operators) |
| Best for | Local dev, CI/CD, single-host prod | Multi-node production, enterprise scale |
Compose wins: Teams just starting with containers, local development workflows, CI/CD pipelines, single-server deployments, and prototyping. The mental model is simple and the configuration is straightforward.
Kubernetes wins: Production at scale requiring multi-node scheduling, automatic failover, sophisticated traffic management, compliance requirements (RBAC, audit logs, network policies), and teams with dedicated DevOps capacity.
Security and Compliance Notes
Docker Compose security extends Docker hardening principles to multi-container applications. A docker-compose.yml that exposes unnecessary ports or runs as root defeats the security model you have worked to build in your Dockerfiles.
Image Security
Every service in your compose file pulls an image. Validate that each image comes from a trusted source and is scanned for vulnerabilities. In your compose file, pin image tags explicitly rather than relying on latest. An image tagged postgres:15-alpine today may receive security patches that change behavior silently.
services:
db:
# Pin exact version for reproducibility
image: postgres:15.4-alpine
Configure vulnerability scanning in your CI pipeline before images reach your compose environments. Trivy or Snyk can scan images at the build stage and block deployment if critical CVEs are found.
Secrets in Compose Files
The security_opt directive applies security hardening to containers. The no-new-privileges flag prevents containers from gaining additional privileges after startup. The cap_drop directive removes unnecessary Linux capabilities. Compose secrets can mount a file into selected services, but a local file-backed secret is not a managed production secret store; protect the source file and use a secret manager when central rotation or audit is required.
services:
web:
image: myapp:1.0.0
security_opt:
- no-new-privileges:true
cap_drop:
- ALL
user: "10001"
read_only: true
tmpfs:
- /tmp:rw,noexec,nosuid,size=64m
Network Isolation
Create custom networks to isolate services by trust boundary. A database should not be directly reachable from the internet-facing web service. Network segmentation ensures that even if the web service is compromised, the attacker cannot reach the database directly.
services:
web:
networks:
- frontend
api:
networks:
- frontend
- backend
db:
networks:
- backend
# Database not reachable from frontend network
networks:
frontend:
driver: bridge
backend:
driver: bridge
internal: true # No external access
The internal: true flag creates a fully isolated network with no external connectivity. Only services explicitly attached can communicate, and none of them can reach external networks.
TLS for Service Communication
For services that communicate over HTTP within the compose stack, use TLS certificates to encrypt traffic. In development, generate self-signed certificates. In production, use certificates from a trusted CA.
services:
api:
image: myapi:1.0.0
volumes:
- ./certs:/etc/certs:ro
environment:
- SSL_CERT_FILE=/etc/certs/api.crt
- SSL_KEY_FILE=/etc/certs/api.key
Audit Logging
Track changes to your compose files and the images they reference. Version control your docker-compose.yml files and require peer review for changes. Enable logging on the Docker daemon to capture container lifecycle events.
# Configure log rotation in daemon.json
{
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
}
}
Compliance Considerations
Immutable infrastructure means your compose files describe a specific versioned stack. If you need to audit what was running at a specific point in time, version control history combined with image tags gives you that traceability.
Access control for compose files should restrict who can modify service definitions, network configurations, and volume mounts. A modified compose file that removes network isolation or adds unnecessary privileges is a security incident waiting to happen.
Resource limits in production compose files prevent one service from consuming all available CPU or memory. Without limits, a runaway service can destabilize the entire stack.
Interview Questions
depends_on and condition: service_healthy in Docker Compose?depends_on only waits for the container to start, not for the service inside to be ready. A database container might be running but still initializing. condition: service_healthy uses a health check you define to wait until the service is actually ready to accept connections before starting dependent services. This prevents race conditions where your API tries to connect to the database before it is ready.
Compose can mount file-backed secrets at /run/secrets/secret_name for selected services. With local Compose, the source file remains on the host and Compose does not provide a central, encrypted secret manager. Keep that file out of version control and restrict access; use a production secret manager if you need managed rotation or audit. Swarm secrets have separate storage and lifecycle guarantees.
Compose creates a default bridge network for your stack. All services on the default network can reach each other by service name. To isolate services, create custom networks and assign services to specific networks. Services on different networks cannot communicate unless you explicitly connect them. This lets you create security boundaries — for example, a database-only network that the frontend cannot reach directly, only the backend service can.
docker compose up and docker compose up -d?docker compose up runs services in the foreground, interleaving logs from all services in your terminal. This is useful for development. docker compose up -d runs services in the background (detached mode), returning control to your terminal immediately. In detached mode, you use docker compose logs -f to follow logs and docker compose ps to check status.
Use docker compose up -d --scale web=3 to run 3 replicas of the web service. However, port mapping becomes problematic with scaling — you cannot map the same host port to multiple containers. So scaling only works for services that do not expose ports directly or when you use a load balancer in front of the scaled services. For true load balancing and auto-scaling, you need Kubernetes. Compose scaling is useful for workers and background tasks that do not need port exposure.
Use multiple Compose files with the -f flag to layer configuration. A base compose.yaml can hold common settings; an override file can add production-specific image tags, restart policies, or resource limits. Run docker compose -f compose.yaml -f compose.prod.yaml up -d. Later files override or extend earlier ones according to Compose merge rules.
Check which UID/GID the process uses and the ownership of the mounted path. If the image changed its runtime user, the volume may still be owned by the previous UID. Keep the runtime UID stable or perform a reviewed ownership migration after taking a backup. Do not use docker compose down -v as a permissions fix; it deletes named volume data.
First, verify the service name resolves: docker compose exec web ping api. Check the DNS configuration inside the container: docker compose exec web cat /etc/resolv.conf. If DNS is working but resolution fails, the service name might have a typo or the target service might not be on the same network. Use docker compose exec web nslookup api for more detail. Restarting the network (docker compose down && docker compose up -d) often clears stale DNS cache entries.
Signs you are outgrowing Compose: you need to run on multiple nodes (Compose is single-host), you need automatic load balancing and self-healing beyond container restart, your rolling update process requires complex scripts, you need multi-environment consistency with different configs, or your service count exceeds what you can manage with manual networking. The migration is not trivial — Compose concepts translate but the tooling differs significantly. Start Kubernetes migration when the pain of managing Compose outweighs the learning investment of Kubernetes.
Bind mounts map a host directory into the container — changes on host and container are immediate. Use for source code during development (hot reload). Named volumes are managed by Docker — data persists across container restarts and is isolated from host filesystem. Use for application data (databases, logs) where you want Docker to manage ownership and lifecycle. Bind mounts are simpler for development; named volumes are more reliable for persistent data in production.
depends_on ensures services start in the correct order—db starts before web and api. However, depends_on only waits for the container to start, not for the service inside to be fully ready. If db takes 30 seconds to initialize the database, web will try to connect before the database is ready. Use healthcheck with condition: service_healthy to make dependent services wait until the service is genuinely ready to accept connections. This prevents application errors from race conditions at startup.
docker compose up creates containers if they do not exist, recreates them if they have changed (configuration drift), and starts them. It also builds images if build: is defined. docker compose start only starts existing containers that were previously created but stopped—it does not create missing containers or rebuild images. Use up for initial startup and after configuration changes; use start for resuming stopped containers without rebuilding.
Use named volumes defined at the top level of the compose file under volumes:. Volumes persist data outside the container's filesystem—Container restarts do not affect volume data. For databases and application state, always use named volumes rather than bind mounts. For source code during development, bind mounts let you edit files on your host and see changes immediately inside the container. The volumes: section defines volume names; services mount them by name under their volume configuration.
The top-level version field is obsolete. Current Compose implementations ignore it and validate the file against the Compose Specification, so omit it from new files. See the official version reference.
Compose reads interpolation values from the shell and a project .env file. Put configuration references such as ${VAR_NAME} in the Compose file, and pass the values to a service only when it needs them. A local .env file is not encrypted storage: keep credentials out of version control, protect file permissions, and prefer mounted secrets or a production secret manager for sensitive values.
bridge is the default network mode—Docker creates a virtual bridge network where containers can communicate by service name. host mode removes network isolation and attaches the container directly to the host's network stack (useful for performance-sensitive workloads). overlay networks connect containers across multiple Docker hosts (requires Swarm mode or Docker in swarm mode). For most Compose usage, the default bridge network works fine. Use custom bridge networks for service isolation by trust boundary—for example, a database-only network that frontend services cannot access directly.
Start with docker compose logs <service-name> to see what the service printed before failing. Check docker compose ps to see the actual status of all services. Run docker compose config to validate the compose file is parsed correctly. If the container keeps restarting, use docker compose exec <service> sh to get an interactive shell and inspect the environment. For network issues, test DNS resolution: docker compose exec web ping api. For permission issues, check volume ownership with ls -la on the host and verify the container user with docker compose exec web id.
Docker Compose creates a DNS resolver that maps service names to container IP addresses. When web reaches postgres://db:5432/app, Docker's embedded DNS resolves db to the IP address of the container running the db service. This only works within the same Docker network—services on different networks cannot resolve each other by name. For multi-host setups, use overlay networks (Swarm mode) or an external service discovery mechanism like Consul or etcd.
docker compose down stops and removes containers and Compose-managed networks. It preserves named volumes by default. Adding -v removes named volumes declared in the Compose file, so use that option only when you intend to delete their data. docker compose rm removes stopped service containers without removing the project networks or volumes.
Use deploy.resources.limits for CPU and memory constraints where the deployment platform implements those fields. Compose treats the deploy section as optional, so check the behavior of the target runtime. Choose limits from observed workload needs and leave enough capacity for the host and other services. See the Compose Deploy Specification.
Further Reading
Docker Compose Patterns for Production
Health check orchestration: Compose can wait for services to be healthy before starting dependencies using condition: service_healthy. This works with custom health checks and is more reliable than simple depends_on ordering.
services:
api:
depends_on:
db:
condition: service_healthy
db:
healthcheck:
test: ["CMD-SHELL", "pg_isready -U user -d app"]
interval: 5s
timeout: 3s
retries: 5
Restart policies: Use restart: unless-stopped for production services that should automatically recover from crashes. Alternatives: always (restart always), on-failure (restart on non-zero exit), no (never restart).
Resource limits: Set memory and CPU limits per service to prevent one service from starving others. Docker Compose applies these via the container runtime.
services:
api:
deploy:
resources:
limits:
memory: 512M
cpus: "0.5"
reservations:
memory: 256M
cpus: "0.25"
- Docker Compose Documentation - Official compose reference
- Compose Specification - Current Compose file reference
- Docker Compose releases - CLI release history
- Compose Deploy Specification - CPU and memory deployment constraints
- Compose Environment Variables - Managing config with env vars
- Docker Secrets Documentation - Using secrets in Swarm mode
- Docker networking guide - Network drivers and port publishing
- Docker volumes guide - Persistent container storage
- Docker fundamentals tutorial - Build and run a complete local sample
- Docker Compose on Docker Docs - Current Compose documentation
Conclusion
Before starting the stack, check that:
- Define services, networks, and volumes in a
compose.yamlfile - Use
depends_onwithcondition: service_healthyfor service startup ordering - Keep credentials out of YAML and images; use a local secret file for development and an appropriate secret manager in production
- Set resource limits (memory, CPU) for each service
- Add health checks to critical services
- Use separate Compose files for dev/staging/prod (
-f docker-compose.yml -f docker-compose.prod.yml) - Never commit secrets or environment files with credentials to version control
- Test your Compose configuration with
docker compose configbefore running - Monitor container resource usage with
docker stats - Log to stdout/stderr and let Docker handle log aggregation
Category
Related Posts
Multi-Stage Builds: Minimal Production Docker Images
Learn how Docker multi-stage builds separate build-time tools from runtime files, with practical guidance for caching, secrets, non-root containers, and image attestations.
Docker Fundamentals: Build and Run a Containerized App
Build a small Node.js container with Docker, run it through Compose, check its health, and confirm that its named volume keeps data across restarts.
Container Images: Building, Optimizing, and Distributing
Learn how Docker container images work, layer caching strategies, image optimization techniques, and how to publish your own images to container registries.