DEV Community


Posted on

Load balancing with Docker Swarm & Nginx

Docker Swarm is a platform that enables deployment and hosting of clusters of docker hosts. Nginx is a web server that offers different services such as HTTP caching, load balancing, reverse proxying as well as mail proxying.
Load balancing is the distribution of equal resources across different servers to improve the performance of an application.

Let's say you're a teacher with a classroom full of students who all need your help at the same time. You have a big stack of papers to grade, questions to answer, and projects to review. If every student lines up in front of your desk to ask for help or submit their work, it's going to be chaotic and slow. Some students might have to wait a long time before they get the attention they need.
Load balancing in this scenario would be like having teaching assistants or group leaders who can help manage the workload. Each assistant can take a group of students and handle their questions, grade their papers, and provide feedback. This way, the workload is distributed among multiple helpers, making sure that everyone gets the support they need promptly without overwhelming you, the teacher.

This article will explore how to achieve load balancing with Nginx and Docker Swarm.


  1. Docker & Docker swarm installed.
  2. Nginx installed.

Step 1: Start with creating a folder where your application will run and initialize Docker swarm. docker swarm init

Docker swarm initialized

Step 2: Create a Docker service with the name of your application, replicas needed ports, and image needed. We will use alpine as the choice of image. docker service create --name yourappname --replicas 2 -p 8080:80 httpd:alpine


Docker service added

Step 3: Configure nginx at the ‘’/etc/nginx/sites-available/default’’ file location with the following variables.

server {
listen 80;
server_name localhost;

location / {
    proxy_pass http://localhost:8080;  
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
Enter fullscreen mode Exit fullscreen mode



Step 4: Save the configurations and restart the Nginx service.sudo systemctl restart nginx

Step 5: Go to the load balancing service using http://localhost or the IP address of your device. The screenshot displays that the site is actively working.

Localhost shows up

Nginx acts as the load balancer for the Docker swarm. It forwards traffic to the Docker swarm services running at port 8080


In conclusion, we were able to create a Docker swarm service that used Nginx to forward packets and offer load balancing to the traffic in the application. Docker swarm offers a versatile tool for clustering and orchestration of Docker containers.

Top comments (0)