π Scaling Services with Docker Compose
Scaling services with Docker Compose is a great way to simulate load balancing and improve availability. Hereβs a step-by-step guide to scaling a web service in a multi-container application.
Step 1: Create a Multi-Container Application
We'll define a web service using Nginx and a load balancer with Nginx.
Directory Structure
docker-compose-scaling/
βββ docker-compose.yml
βββ web/
β βββ Dockerfile
β βββ index.html
βββ nginx.conf
Step 2: Define the Web Service
Dockerfile for the Web Service (web/Dockerfile
)
FROM nginx:latest
COPY index.html /usr/share/nginx/html/index.html
Explanation:
-
FROM nginx:latest
β Uses the official Nginx image as the base image. -
COPY index.html /usr/share/nginx/html/index.html
β Copies the HTML file into the default Nginx directory.
Sample HTML Page (web/index.html
)
<!DOCTYPE html>
<html>
<head>
<title>Scaled Web Service</title>
</head>
<body>
<h1>Welcome to the Scaled Web Service</h1>
</body>
</html>
Step 3: Define docker-compose.yml
version: '3'
services:
web:
image: nginx # Using Nginx as a web server
deploy:
replicas: 3 # Scale to 3 instances
volumes:
- ./web:/usr/share/nginx/html # Mount your web app files (index.html)
networks:
- webnet
load_balancer:
image: nginx
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro # Custom Nginx config for load balancing
ports:
- "8081:80" # Exposing only the load balancer to avoid port conflicts
depends_on:
- web
networks:
- webnet
networks:
webnet:
Explanation:
-
web
service runs three replicas of Nginx. -
load_balancer
uses Nginx for load balancing. - Services communicate via
webnet
.
Step 4: Configure Load Balancer
Nginx Configuration (nginx.conf
)
events {}
http {
upstream web_backend {
server web:80;
server web:80;
server web:80;
}
server {
listen 80;
location / {
proxy_pass http://web_backend;
}
}
}
Step 5: Scale the Service Using Docker Compose
Run the following command to start and scale the service:
docker-compose up --scale web=3 -d
Step 6: Test the Scaled Application
Open your browser and visit:
http://localhost:8081
Check running containers:
docker ps
How Load Balancing Works
- When multiple instances of a service run, requests are distributed among them.
- Nginx acts as a reverse proxy and uses round-robin to distribute traffic.
Top comments (0)