准备好三台安装了nginx的虚拟机,ip分别为 135、136、137。


实战演示:
- 1.# 分别修改三台nginx的默认站点
- [root@nginx01 ~]# vim /usr/local/nginx/html/index.html
- Hello,192.168.78.135
-
- 2.# 修改nginx01的配置文件
- [root@nginx01 ~]# vim /usr/local/nginx/conf/nginx.conf
-
- worker_processes 1;
-
- events {
- worker_connections 1024;
- }
-
-
- http {
- include mime.types;
- default_type application/octet-stream;
-
-
- sendfile on;
-
- keepalive_timeout 65;
-
- # 虚拟主机1
- server {
- listen 80;
- server_name localhost;
-
-
- location / {
- # 反向代理
- proxy_pass http://192.168.78.136; # 输入需要访问的目标地址或者域名
- # root html; # 默认访问 proxy_pass模块,下面部分不在访问
- # index index.html index.htm;
- }
-
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
-
- }
-
-
- }
-
- 3.# 重装 nginx
- [root@nginx01 ~]# systemctl reload nginx.service
测试效果:
在浏览器输入nginx01的ip地址(135),成功访问到 136 站点
实战演示:
- [root@nginx01 ~]# vim /usr/local/nginx/conf/nginx.conf
-
- worker_processes 1;
-
- events {
- worker_connections 1024;
- }
-
-
- http {
- include mime.types;
- default_type application/octet-stream;
-
-
- sendfile on;
-
- keepalive_timeout 65;
-
- # 负责均衡集群
- upstream httpds { # httpds 可自定义名称
-
- # 80端口默认可省略
- server 192.168.78.136:80;
- server 192.168.78.137:80;
-
- }
-
- # 虚拟主机1
- server {
- listen 80;
- server_name localhost;
-
-
- location / {
- # 反向代理
- proxy_pass http://httpds; # 需与 upstream 定义的名称一致
- # root html;
- # index index.html index.htm;
- }
-
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
-
- }
-
-
- }
-
- [root@nginx01 ~]# systemctl reload nginx.service
测试效果:
在浏览器输入nginx01的ip地址(135),重复刷新,可以成功访问到 136、137 站点

默认情况下使用轮询方式,逐一转发,这种方式适用于无状态请求。如上述的负载均衡配置
指定轮询几率,weight和访问比率成正比,用于后端服务器性能不均的情况。
- upstream httpds {
-
- server 192.168.78.136:80 weight=8 down;
- server 192.168.78.137:80 weight=2;
- server 192.168.78.137:80 weight=2 backup;
- }
weight 可选参数:
以下几种不常用:
3.ip_hash
根据客户端的ip地址转发同一台服务器,可以保持回话。
4.least_conn
最少连接访问
5.url_hash
根据用户访问的url定向转发请求
6.fair
根据后端服务器响应时间转发请求