Defining Services in Compose
Imagine building a city blueprint. Each building (service) has its own role: a hospital, a school, a power station. In Docker Compose, services are those buildings - each one represents a container with a specific purpose. By defining services, you tell Docker how to construct and connect the pieces of your application.
Services Foundations
1. What is a Service in Compose?
- A service is a container definition inside
docker-compose.yml. - Each service specifies the image, build context, ports, environment variables, volumes, and dependencies.
- Services can be scaled to multiple replicas.
2. Common Service Configuration Options
- restart: Controls restart policy (
always,on-failure,unless-stopped).
depends_on: Defines service dependencies.
depends_on:
- db
volumes: Mounts host directories or named volumes.
volumes:
- dbdata:/var/lib/mysql
environment: Sets environment variables.
environment:
- MYSQL_ROOT_PASSWORD=secret
ports: Maps host ports to container ports.
ports:
- "8080:80"
build: Builds an image from a Dockerfile.
build: ./app
image: Defines which image to use.
image: nginx:latest
3. Service Dependencies
- Services can depend on each other (e.g., a web app depends on a database).
- Compose ensures dependent services start in the right order.
4. Scaling Services
- Services can be scaled horizontally.
- Runs three replicas of the
webservice.
docker-compose up --scale web=3
Things to Remember
- Services are the core building blocks of Compose.
- Each service defines how a container should run.
- Dependencies and scaling make services powerful for microservices.
Hands‑On Lab
Step 1: Define a Web + DB Stack
version: '3'
services:
web:
image: nginx
ports:
- "8080:80"
depends_on:
- db
db:
image: mysql:5.7
environment:
- MYSQL_ROOT_PASSWORD=secret
volumes:
- dbdata:/var/lib/mysql
volumes:
dbdata:
Step 2: Run the Stack
docker-compose up -d
Step 3: Verify Services
docker-compose ps
Step 4: Scale the Web Service
docker-compose up -d --scale web=3
Practice Exercise
- Create a
docker-compose.ymlfile with three services:frontend(nginx) exposed on port 8081.backend(node.js app built from a Dockerfile).database(mysql with environment variables).
- Define dependencies (
frontenddepends onbackend,backenddepends ondatabase). - Run the stack and confirm all services are connected.
- Scale the
frontendservice to 2 replicas.
Visual Learning Model
docker-compose.yml
├── Service: frontend → port 8081
├── Service: backend → depends on database
└── Service: database → persistent volume
The Hackers Notebook
Defining services in Compose is about describing how each container should run. Services specify images, builds, ports, environment variables, volumes, and dependencies. With scaling and restart policies, services become the foundation for building resilient, multi‑container applications.
