How to realize a simple load balancing by using nginx and docker

11-08-2023

Test steps:

1. Build a nginx server in the server and start it.

2. Pull the official image of nginx from the source in docker, and keep it for later use.

3. Create two new folders in the local directory. My new folder is in /mydata/test1, /mydata/test2/

4. Create new index.html symbols in two test folders respectively, output this is nginx1 in the first html and this is nginx2 in the second html.

5. Run the containers of two nginx servers through docker, and map the static directories to the directories we just created.

6. Modify the configuration file of nginx in the host.

Add the following code in http{}

Upstream myweb {#myproject is a custom name #ip_hash; # On means ip address allocation, which can solve the sesson problem: server 127.0.0.1:8080 weight=1; The greater the #weight, the higher the weight, and the greater the probability of being allocated; server 127.0.0.1:8081 weight=1; # I'm all in this machine, so I use the local ip, just change it to the corresponding ip or domain name}

7. Enter the conf.d directory and modify the default.conf (there is no new file in conf.d, the file name is optional, and the suffix must be. conf).

Location/{# If the server wants to obtain the real ip of the client, it can set the host header and the real address of the client #proxy_set_header host $host; #proxy_set_header x-real-ip $remote_addr; #proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; root /usr/share/nginx/html; index index.html index.htm ;  proxy_pass http://myweb; #myweb is the name defined after upstream in nginx.conf}

8. After saving, exit and restart the server: systemctl restart nginx.

9. Enter the current domain name through the browser, and refresh the page, sometimes output nginx1, sometimes output nginx2, and the configuration is successful.

Copyright Description:No reproduction without permission。

Knowledge sharing community for developers。

Let more developers benefit from it。

Help developers share knowledge through the Internet。

Follow us