Abstract:
This example will show how to config a simple Nginx loading balance with Round-Robin policy, which involves 4 node servers to run web app and 1 nginx server to do load balance. Now, I will demonstrate this case with Docker.
Configuration:
1. Setup 4 app servers
Since I already programmed a simple web app with Springboot and published it as Docker Image, it is quite easy to launch the 4 node servers by calling following commands in 4 times.
docker run -it -d yexianyi/chukonu-springboot
If we exec to these nodes, we will get their service urls:
http://172.17.0.3:9000
http://172.17.0.4:9000
http://172.17.0.5:9000
http://172.17.0.6:9000
2. Setup and config Nginx
1) The installation process will be ignored and you may refer to my pervious blog for details.
2) config /etc/nginx/nginx.conf
2.1) create upstream under http section:
upstream tomcat-pool {
server 172.17.0.3:9000;
server 172.17.0.4:9000;
server 172.17.0.5:9000;
server 172.17.0.6:9000;
}
Note that underline "_" is not supported, so we use dash "-" instead.
2.2) Config Server Section
server {
listen 8080;
server_name localhost;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://tomcat-pool;
}
#Other config are ignored
#...
}
listen: the port number will be used for access service.
server_name: the server address will be used for access service.
proxy_pass: the upstream name we create in step 2.1.
2.3) Save above update
2.4) Refresh config by invoking following command
/usr/sbin/nginx -s reload
3. Testing
Now, there is a rest service published on endpoint http://<server_ip>:<port>/function/local_ip, which will display the underlying server address. For example, if we call http://localhost:8080/function/local_ip several times, the result should be populated from 172.17.0.3 to 172.17.0.6 in a RR way, such as
{"address":"172.17.0.3"}
{"address":"172.17.0.4"}
{"address":"172.17.0.5"}
{"address":"172.17.0.6"}
{"address":"172.17.0.3"}
{"address":"172.17.0.4"}
{"address":"172.17.0.5"}
{"address":"172.17.0.6"}
{"address":"172.17.0.3"}
Appendix:
My webapp docker image: yexianyi/chukonu-springboot