1.需要准备3台服务器,并安装好Nginx
10.0.0.3 nginx 负载均衡服务器
10.0.0.8 后端业务服务器1
10.0.0.9 后端业务服务器2
2.查看Nginx原参数
[root@localhost ~]# /data/nginx/sbin/nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/data/nginx --with-http_ssl_module --with-http_gzip_static_module --with-http_stub_status_module
3.安装echo测试模块
[root@localhost ~]# wget -c https://github.com/openresty/echo-nginx-module/archive/v0.61.tar.gz #下载echo测试模块
[root@localhost ~]# tar xzf v0.61.tar.gz -C nginx-1.16.1 #解压echo测试模块
[root@localhost nginx-1.16.1]# ./configure --prefix=/data/nginx --add-module=echo-nginx-module-0.61 #预编译echo测试模块
[root@localhost nginx-1.16.1]# make #编译(不需要编译安装)
[root@localhost nginx-1.16.1]# mv /data/nginx/sbin/nginx /data/nginx/sbin/nginx.old #重命名原执行文件
[root@localhost nginx-1.16.1]# cp objs/nginx /data/nginx/sbin/nginx #拷贝新nginx执行文件至nginx目录
[root@localhost nginx-1.16.1]# make upgrade
4.安装echo测试模块完成
[root@localhost nginx-1.16.1]# /data/nginx/sbin/nginx -V
nginx version: nginx/1.16.1
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (GCC)
configure arguments: --prefix=/data/nginx --add-module=echo-nginx-module-0.61
5.启动3台服务器的nginx并测试是否能正常ping通。
[root@localhost ~]# systemctl stop firewalld.service && /data/nginx/sbin/nginx #关闭防火墙并启动nginx
[root@localhost ~]# ping 10.0.0.8
PING 10.0.0.8 (10.0.0.8) 56(84) bytes of data.
64 bytes from 10.0.0.8: icmp_seq=1 ttl=64 time=0.748 ms
64 bytes from 10.0.0.8: icmp_seq=2 ttl=64 time=0.257 ms
64 bytes from 10.0.0.8: icmp_seq=3 ttl=64 time=0.246 ms #可正常连接
[root@localhost ~]# ping 10.0.0.9
PING 10.0.0.9 (10.0.0.9) 56(84) bytes of data.
64 bytes from 10.0.0.9: icmp_seq=1 ttl=64 time=0.924 ms
64 bytes from 10.0.0.9: icmp_seq=2 ttl=64 time=0.243 ms
64 bytes from 10.0.0.9: icmp_seq=3 ttl=64 time=0.267 ms #可正常连接
6.配置nginx.conf文件
1️⃣10.0.0.3 nginx 负载均衡服务器
upstream www{
server 10.0.0.8:80;
server 10.0.0.9:80;
}
server {
listen 80;
server_name www.test.com;
root html;
index index.html;
location / {
proxy_pass http://www;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
2️⃣10.0.0.8 后端业务服务器1
server {
listen 80;
server_name localhost;
root /tmp/123.com_8080;
index index.html;
location / {
echo "gdl1";
}
3️⃣10.0.0.9 后端业务服务器2
server {
listen 80;
server_name localhost;
root /tmp/123.com_8080;
index index.html;
location / {
echo "gdl2";
}
并重启3台服务器的nginx服务
[root@localhost conf]# /data/nginx/sbin/nginx -s reload
7.测试10.0.0.3是否正常进行负责均衡
[root@localhost conf]# curl www.test.com
gdl1
[root@localhost conf]# curl www.test.com
gdl2
[root@localhost conf]# curl www.test.com
gdl1
[root@localhost conf]# curl www.test.com
gdl2
[root@localhost conf]# curl www.test.com
gdl1
[root@localhost conf]# curl www.test.com
gdl2
访问10.0.0.3可以正常转发至后端服务器,并进行轮询访问后端服务器。