Service Configuration
Docker Compose Overview
Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to use a YAML file to configure your application's services, networks, and volumes.
Compose File Structure
version: '3.8'
services:
web:
image: nginx:latest
ports:
- "80:80"
database:
image: postgres:13
environment:
POSTGRES_PASSWORD: example
Configuration Parameters
Key Configuration Sections
Section |
Purpose |
Example |
version |
Compose file format version |
3.8 |
services |
Define containers |
web, database |
networks |
Create custom networks |
frontend, backend |
volumes |
Persistent data storage |
database_data |
Service Definition Detailed Example
version: '3.8'
services:
## Web application service
web:
image: nginx:latest
container_name: web-server
ports:
- "8080:80"
volumes:
- ./website:/usr/share/nginx/html
networks:
- web_network
restart: always
## Database service
database:
image: postgres:13
container_name: postgres-db
environment:
POSTGRES_DB: myapp
POSTGRES_USER: admin
POSTGRES_PASSWORD: securepassword
volumes:
- postgres_data:/var/lib/postgresql/data
networks:
- web_network
restart: unless-stopped
networks:
web_network:
driver: bridge
volumes:
postgres_data:
Service Configuration Management
graph TD
A[Docker Compose YAML] --> B{Validate Configuration}
B --> |Valid| C[Build Services]
B --> |Invalid| D[Show Error]
C --> E[Start Containers]
E --> F[Monitor Services]
Advanced Configuration Techniques
Environment Variables
## Create .env file
echo "DB_PASSWORD=mysecretpassword" > .env
## Reference in docker-compose.yml
environment:
- DB_PASSWORD=${DB_PASSWORD}
Health Checks
services:
web:
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost"]
interval: 30s
timeout: 10s
retries: 3
Common Configuration Commands
## Validate compose file
docker-compose config
## Start services
docker-compose up -d
## Stop services
docker-compose down
## View service logs
docker-compose logs web
## Rebuild services
docker-compose up -d --build
Best Practices
- Use environment-specific compose files
- Implement proper volume management
- Use networks for service isolation
- Leverage environment variables
- Implement health checks
Note: LabEx provides interactive environments to practice these Docker Compose configurations effectively.