DEV Community

Kishore Suzil
Kishore Suzil

Posted on

1 1 1

Scaling Services with Docker Compose

πŸš€ 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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. FROM nginx:latest β†’ Uses the official Nginx image as the base image.
  2. 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>
Enter fullscreen mode Exit fullscreen mode

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:
Enter fullscreen mode Exit fullscreen mode

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;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Step 6: Test the Scaled Application

Open your browser and visit:

http://localhost:8081
Enter fullscreen mode Exit fullscreen mode

Check running containers:

docker ps
Enter fullscreen mode Exit fullscreen mode

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)