logo

Setting Up Nginx in a Docker Container as a Load Balancer

O

Ohidur Rahman Bappy

MAR 22, 2025

Introduction

In this tutorial, you'll learn how to configure an Nginx Docker container to function as a load balancer. This setup will distribute incoming requests to two application instances in a round-robin manner.

Prerequisites

Ensure you have the following:

  • Docker installed
  • Basic knowledge of Nginx and Docker

Application Instances

We have two instances of the application running on:

  • 192.168.1.250:2221
  • 192.168.1.250:3331

Requests arriving at the Nginx server on port 8080 will be forwarded to these instances.

Nginx Configuration (nginx.conf)

Create a configuration file for Nginx to handle load balancing.

http {
    upstream all {
        server 192.168.1.250:2221;
        server 192.168.1.250:3331;
    }

    server {
         listen 8080;
         location / {
              proxy_pass http://all/;
         }
    }
}

events { }

Dockerfile (Dockerfile)

Create a Dockerfile to build the Nginx image with your configuration.

FROM nginx
COPY nginx.conf /etc/nginx/nginx.conf

Building and Running the Docker Container

Follow these steps to build and run your Nginx load balancer container:

  1. Create a directory for your Nginx load balancer and navigate into it:

    mkdir nginx-load-balancer
    cd nginx-load-balancer
    
  2. Create the nginx.conf and Dockerfile with the configurations above.

  3. Build the Docker image:

    docker build -t nginxlb .
    
  4. Run the Docker container:

    docker run -d --name nginx-load-balancer -p 8087:8080 nginxlb
    

Conclusion

Your Nginx container is now set up to balance the load between two application instances. This setup will improve application reliability and scalability.