Defining Services in Compose
What you'll learn: How to declare individual container services in a docker-compose.yml file with images, build contexts, and essential configuration options.
The Core Concept
In Docker Compose, a service represents a containerized component of your application. Each service definition tells Compose how to create and configure one or more containers of the same type. Think of a service as a blueprint: it specifies which image to use, how to build it, what ports to expose, and other runtime settings.
Key Service Properties
When defining a service, you typically include:
image: The pre-built container image to use (e.g.,nginx:latest)build: Alternatively, a path to a Dockerfile and build context for custom imagesports: Map container ports to host ports for external accessenvironment: Set environment variables for configurationvolumes: Attach persistent storage or bind mounts
Basic Example Structure
services:
web:
image: nginx:alpine
ports:
- "8080:80"
environment:
- ENV_VAR=value
api:
build: ./api
ports:
- "3000:3000"
volumes:
- ./data:/app/data
In this example, web uses a pre-built image while api builds from a local Dockerfile. Each service becomes one or more containers when you run docker-compose up.
The Analogy
Think of services like actors in a play. The docker-compose.yml file is your script, defining each actor's role (image/build), costume (environment variables), props (volumes), and stage position (ports). Compose orchestrates them all to work together.
Key Takeaway: Services in Docker Compose define containerized application components using image references or build contexts, along with configuration options like ports, environment variables, and volumes—creating a declarative blueprint for multi-container deployments.