How to use Nginx proxy server in Docker to achieve load balancing of multiple web servers?
Abstract:
In the architecture of modern web applications, load balancing is an important topic. By distributing traffic across multiple servers, you can improve system availability, performance, and scalability. This article will introduce how to use Docker and Nginx proxy server to achieve load balancing of multiple web servers.
FROM nginx:latest COPY index.html /usr/share/nginx/html/ COPY nginx.conf /etc/nginx/nginx.conf EXPOSE 80
Here, we use the official image provided by Nginx and copy the files index.html and nginx.conf to the corresponding locations. In index.html, you can place any web content you want to display. In nginx.conf, you can configure Nginx related settings.
http { upstream backend { server web1:80; server web2:80; } server { listen 80; location / { proxy_pass http://backend; proxy_set_header Host $host; } } }
Here, we define an upstream server group named backend, which contains the addresses of the two web servers. In the server block, we bind port 80 to the Nginx proxy server and proxy traffic to the backend server group. The proxy_set_header directive is used to set the Host header of the request to the address of the server.
First, we need to build the web server image. In the directory where the image is located, run the following command.
docker build -t web-server .
Then, we can run multiple web server instances. Run the following command twice to create two instances.
docker run -d --name web1 web-server docker run -d --name web2 web-server
Next, we need to create an Nginx proxy server instance. Run the following command.
docker run -d -p 80:80 --name nginx-proxy --link web1 --link web2 nginx
Here, we used the --link parameter to connect the Nginx proxy server to the two web server instances.
By looking at the logs of the web server container, we can see how requests are distributed to different instances.
docker logs web1 docker logs web2
Conclusion:
By using Docker and Nginx proxy server, we can easily achieve load balancing of multiple web servers. This method is not only simple and efficient, but also highly flexible and scalable. I hope this article can be helpful to you, thank you for reading!
The above is the detailed content of How to use Nginx proxy server in Docker to achieve load balancing of multiple web servers?. For more information, please follow other related articles on the PHP Chinese website!