Nginx Configuration of loading balance

本文介绍如何使用Docker快速部署四个Spring Boot应用服务器,并通过Nginx实现Round-Robin轮询策略进行负载均衡。文章详细展示了配置过程,包括设置四个节点服务器、配置Nginx上游服务器池以及测试负载均衡效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yexianyi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值