How Do You Use the ip_hash Directive in Nginx Running in Docker and Be Able to Stop and Start the Docker Container Again?

Problem scenario
You are using Nginx as a reverse proxy (a server that is essentially a landing page that is invisible to users and passes connection requests to other web servers like a router).  You noticed that when you added the "ip_hash;" directive in the "upstream server {}" section (also known as a block) of the /etc/nginx/conf.d/default.conf file, you lose the Docker container.  That is if you stop the Docker container once the Nginx default.conf file has this "ip_hash;" directive, the Docker container cannot be  restarted again.  What did you do wrong?

Solution
You may have created the Docker container with a user-defined network and IP address.  The Docker container that would have an Nginx default.conf file to receive an ip_hash directive would be a load balancer (or traffic distributor).  Such an Nginx instance distributes traffic and does not act as a web page.  This requires a special way of creating the Docker container with the "docker run" command.

Here is a command to create a Docker container with Nginx that will work as the load balancer:

docker run --name docker-nginxbalancer --net=host nginx

Notice there are no -p flags to configure port mapping, no user-defined networks and no IP addresses in this command.  These three things would be customary for Nginx instances that will render HTML (regular web servers) and be put in the load balancer (in the Nginx default.conf file in the upstream backend {} section thereof).

Leave a comment

Your email address will not be published. Required fields are marked *