Nginx-负载均衡的配置
1、Nginx实现负载均衡需要用到的模块
1.1、ngx_http_upstream_module模块
1.1.1、upstream指令
upstream backend { server backend1.example.com weight=5; server backend2.example.com:8080; server unix:/tmp/backend3; server backup1.example.com:8080 backup; server backup2.example.com:8080 backup; } server { location / { proxy_pass http://backend; } }
1.2、ngx_http_proxy_module模块
1.2.1、proxy_pass 指令
Syntax: proxy_pass URL; Default: — Context: location, if in location, limit_except
2、负载均衡场景环境规划
2.1、负载均衡场景架构图
2.2、准备主机
LB 192.168.10.4 web01 192.168.10.5 web02 192.168.10.7
3、后端Web节点配置实例
3.1、web01配置
3.1.1、准备测试代码
mkdir /opt/web01
echo "web-01" >/opt/web01/index.html
3.1.2、配置nginx
cat >/etc/nginx/conf.d/web01.cyc.com.conf<<'EOF'
server{
listen 8080;
server_name web01.cyc.com;
location / {
root /opt/web01;
index index.html;
}
}
EOF
3.1.3、重新加载nginx并且测试
systemctl restart nginx
~]# curl localhost:8080
web-01
3.2、web02配置
3.2.1、准备测试代码
mkdir /opt/web02 echo "web-02" >/opt/web02/index.html
3.2.2、配置nginx
cat >/etc/nginx/conf.d/web02.cyc.com.conf<<'EOF' server{ listen 8080; server_name web02.cyc.com; location / { root /opt/web02; index index.html; } } EOF
3.2.3、重新加载nginx并且测试
systemctl restart nginx
~]# curl localhost:8080 web-02
4、LB-Nginx配置
4.1、配置常用的代理请求头参数
cat >/etc/nginx/proxy_params<<'EOF' proxy_http_version 1.1; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_connect_timeout 30s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_buffering on; proxy_buffer_size 64k; proxy_buffers 4 64k; EOF # 参考文章:https://www.cnblogs.com/ygbh/p/17365450.html#_label5
4.2、配置nginx
cat >/etc/nginx/conf.d/proxy_web.cyc.com.conf<<'EOF' upstream web { server 192.168.10.5:8080; server 192.168.10.7:8080; } server{ listen 80; server_name web.cyc.com; location / { proxy_pass http://web; include proxy_params; } } EOF
4.3、重新加载nginx
systemctl restart nginx
4.4、配置hosts
echo "192.168.10.4 web.cyc.com" >>/etc/hosts
4.5、测试效果
[root@nfs ~]# curl web.cyc.com web-01 [root@nfs ~]# curl web.cyc.com web-02
# 负载均衡生效