In this lesson, you will learn how to handle increased traffic by dynamically adjusting the number of running replicas for a single service.
When your application becomes popular, a single container might struggle to process all incoming requests. Instead of making the container "bigger" (vertical scaling), we use horizontal scaling to add more identical containers. This distributes the workload across multiple instances, ensuring that no single container becomes a bottleneck.
How Scaling Works
In Docker Compose, scaling is straightforward. When you define a service, you essentially describe a blueprint. To scale, you instruct the orchestrator to spin up additional copies of that blueprint. Because you previously learned about Service Discovery and Embedded DNS, these new containers automatically join the network and become reachable, allowing the orchestrator to balance incoming traffic among them.
Scaling in Action
If you have a service named web-app defined in your docker-compose.yml, you can scale it to five instances using the command line:
docker compose up -d --scale web-app=5
This command tells Docker to ensure exactly five containers of the web-app image are running simultaneously. If you only had one running, it will spin up four more. If you later decide you need to scale back to save resources, you simply run the command with a lower number:
docker compose up -d --scale web-app=2
Why this matters
Horizontal scaling is the backbone of highly available systems. By spreading the load across multiple instances, you protect your application against downtime; if one container fails, the others continue to serve traffic. When combined with your knowledge of Health Checks, the orchestrator will not only ensure you have enough replicas running but will also replace any that become unresponsive, keeping your service healthy and performant.
Key Takeaway: Horizontal scaling allows you to increase or decrease your application's capacity on-demand by spinning up or shutting down identical container replicas, effectively balancing traffic across your infrastructure.