Docker Compose by Example: Service Definitions
Defining multi-container applications with this sample code demonstrating services block structure, image versus build specification, container naming, restart policies, and automatic DNS resolution for inter-service communication.
Code
version: "3.8"
services:
# 1. Define a service named 'web'
web:
# Use an image from Docker Hub
image: nginx:alpine
# Or build from a local Dockerfile
# build: .
# 2. Basic configuration
container_name: my-web-server
restart: always
# 3. Define another service 'db'
db:
image: postgres:15
environment:
POSTGRES_PASSWORD: secretExplanation
The services block forms the core of Docker Compose files, defining individual containers comprising multi-container applications. Each key under services like web or db represents a distinct service that Docker will run. These service names serve dual purposes: identifying the service in Compose commands and providing DNS hostnames for inter-service communication within Docker networks.
Docker Compose automatically creates a default network for applications when running docker compose up. This project-specific network, typically named after the directory with _default appended, uses the bridge network driver. All services defined in the same file automatically connect to this network, enabling seamless communication using service names as hostnames through Docker's built-in DNS server.
Each service requires either an image specification to pull from a registry or a build context to construct an image from source. Runtime parameters like container names, restart policies, and resource limits can be configured declaratively. This approach enables version-controlling entire infrastructure configurations, making deployments reproducible and environments consistent across development, staging, and production.
Code Breakdown
web: service name, other containers reach this at http://web via DNS.image: nginx:alpine specifies image to use, Docker pulls if not present locally.container_name sets custom name, without this Docker generates names like project_web_1.restart: always ensures container restarts automatically on failure or daemon restart.
