Setting Up Nginx in a Docker Container as a Load Balancer
Learn how to configure an Nginx Docker container to balance load across multiple application instances.
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:2221192.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:
-
Create a directory for your Nginx load balancer and navigate into it:
mkdir nginx-load-balancer cd nginx-load-balancer -
Create the
nginx.confandDockerfilewith the configurations above. -
Build the Docker image:
docker build -t nginxlb . -
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.