安装环境:centos7
测试机器:调度机ip:192.168.10.99
server1ip:192.168.11.13 server2ip:192.168.11.179
1.通过nginx自带的upstream模块实现轮询转发访问请求
轮询模式会将调度机收到的请求轮询发送给两个server,比如第一个请求发送给server1,第二个发送给server2,然后第三个请求再发给server1,第四个server2。。。。。。。来实现两个服务器的负载均衡。
实现方法:
三台机器全部安装nginx:
yum install epel-release -y && yum install nginx -y
然后在调度器上的nginx配置文件中的http中的server中的location中加入
proxy_pass http://backend
可以加在nginx目录下的nginx.conf文件下,也可以加在nginx目录下conf.d目录下的文件中。
如下所示:
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 4096;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
listen [::]:80;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
location / {
root /usr/share/nginx/html;
index index.html index.htm;
proxy_pass http://backend;
}
include /etc/nginx/default.d/*.conf;
error_page 404 /404.html;
location = /404.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
接着在conf.d目录下写入文件upstream.conf
cat <<EOF >/etc/nginx/conf.d/upstream.conf
upstream backend {
server 192.168.11.13:80;
server 192.168.11.179:80;
}
EOF
然后重启nginx,关闭防火墙和selinux。访问调度机ip:80即可实现。
systemctl enable nginx && systemctl start nginx
systemctl stop firewalld && setenforce 0
2.加权轮询
此方法和第一种类似,但考虑到了可能后台服务器性能不同,比如我server1的性能比server2要高,所以我给server1一个biserver2要高的比重,让调度器将更多的请求发送给server1去处理。
实现方法与方法一唯一的不用就是在写upstream.conf时,在后面加入了权重:
cat <<EOF >/etc/nginx/conf.d/upstream.conf
upstream backend {
server 192.168.11.13:80 weight=2;
server 192.168.11.179:80 weight=1;
}
EOF
这样的话,在访问请求次数有一定数量之后,server1处理的请求数量与server2处理的请求数量比列大致为2:1。
3.ip_hash
此负载均衡方法,是基于对访问者的ip进行hash解析然后在放松给相应的server,这样相对与前两种方法,多了会话保持的功能
实现方法相对于第一种就是在upstream种加入ip_hash
cat <<EOF >/etc/nginx/conf.d/upstream.conf
upstream backend {
ip_hash;
server 192.168.11.13:80;
server 192.168.11.179:80;
}
EOF