Load Balance Containers Using Nginx

Aishik Saha
Aishik Saha
Published in
3 min readDec 11, 2019

This post describes how to create an Nginx container to load balance other containers running on a user defined network on the same host. Ideally you shouldn’t be doing this and should use Kubernetes. So let’s begin.

Architecture

Step 1

Create a user defined Docker bridge network and name it scale-net.

docker network create --driver bridge scale-net

Once created you can view the network using the command docker network ls.

scale-net is alive!

Step 2

Create two containers to serve web traffic. Let one be Apache and the other be Nginx. We’ll assign the same network we created earlier to them.

docker run -d --name apache1 --network scale-net httpd
docker run -d --name nginx1 --network scale-net nginx

The above command ran both the containers in detached mode with names apache1 and nginx1 on the network scale-net. Check out your containers by running docker ps -a.

Containers created

Step 3

First we’ll get the IP on which our containers are running on. Use the below command.

docker network inspect scale-net

This will output details about the network and containers running on it. Keep note of the IPs, we’ll need them in the next step.

Step 4

Create a new directory using the command mkdir nginx-lb-conf. We’ll save the Nginx loadbalancer configuration here. Then we’ll create a Dockerfile and build the custom Nginx loadbalancer.

Now create the configuration file called nginx.conf and insert the below configuration. Don’t forget to replace the IPs you got in the earlier step.

upstream webapp {server 172.18.0.2:80 weight=1;server 172.18.0.3:80 weight=1;}server {  location / {    proxy_pass http://webapp;  }}

Now create the Dockerfile and insert the below commands.

FROM nginxRUN rm /etc/nginx/conf.d/default.confCOPY nginx.conf /etc/nginx/conf.d/default.conf

Once done, now you can build the Docker image and run it.

docker build -t loadbalancer .
docker run -p 8080:80 -d --network scale-net loadbalancer

Now the Nginx is listening on port 8080 on the host and serving the loadbalanced containers. This can be verified by performing a curl or visiting localhost:8080 on a browser.

Nginx container served on port 8080
Apache container served on port 8080

So now you’ve created an Nginx container that’s loadbalancing other containers on the same network. It is not recommened to use this solution in production. This is just a playful experiment. Use Docker to ship containers and Kubernetes to orchestrate them in production. Or if you’re feeling lucky try out serverless options like Google Cloud Run. 👋

--

--

Aishik Saha
Aishik Saha

Engineer. Interested in machine learning, cloud, containers and open source. Built Slyme (https://5ly.me).