Structuring robust docker-compose.yml for your applications
Building a Solid Foundation Networks, Volumes, and Environment Files
docker-compose.yml.
To ensure isolation and persistent data, custom networks, volumes, and .env files are crucial.
- Define a custom network: This isolates your services.
- Define a named volume: This stores data persistently.
- Create an
.envfile: Put sensitive info here, e.g.,DB_PASSWORD=secret. - Integrate into
docker-compose.yml: - Run Compose:
networks:
my_app_net:
driver: bridge
volumes:
my_app_data:
# .env file
DB_USER=admin
DB_PASSWORD=supersecret
version: '3.8' services: web: image: nginx:latest volumes: - my_app_data:/var/www/html # Bind mount an anonymous volume environment: - DB_USER=${DB_USER} - DB_PASSWORD=${DB_PASSWORD} networks: - my_app_net networks: my_app_net: driver: bridge volumes: my_app_data:
docker-compose up -d
Verification:
- Check networks:
docker network lsYou should see
my_app_net. - Check volumes:
docker volume lsYou should see
<project_name>_my_app_data. - Check service environment variables:
docker exec <container_id> env
Common Failure: Missing .env file or wrong variable name.
Fix: Ensure .env exists and variable names match those in docker-compose.yml exactly.
Ensuring Reliability: Health Checks and Restart Policies
Health checks ensure your services are truly alive. Restart policies dictate how Docker Compose reacts to service failures.
To add a health check:
version: '3.8'
services:
web:
image: nginx
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
start_period: 5s
The test command evaluates the service’s health. CMD runs a command, NONE disables it.
To define restart policies:
services:
web:
image: nginx
restart: always
Common policies:
no: Never restart.on-failure: Restart only if the container exits with a non-zero code.always: Always restart, even on graceful shutdown.unless-stopped: Always restart unless explicitly stopped.
Verify health status with: docker-compose ps or docker ps.
Failure mode: Health checks too strict or too lenient. Adjust interval, timeout, retries, and start_period to match application startup and response times. Incorrect restart policies can lead to services not recovering or constantly restarting. Choose a policy that matches expected service behavior.
These features, combined with robust networking, volumes, and environment management, create a resilient, self-healing Docker Compose environment.
