七层负载均衡(HTTP Load Balancing):基于应用层,nginx默认使用的是七层负载均衡,因为需要看http协议,针对业务来做负载均衡
7层只能给http做负载均衡,4层可以给很多的协议做负载均衡(ftp,MySQL,dns,http等)根据端口来实现,nginx也可以做四层负载均衡
四层负载均衡(TCP and UDP Load Balancing):基于传输层,LVS使用的是四层负载均衡,只需要看端口号,LVS的效率更高,针对业务来做负载均衡
四层负载均衡编译安装的时候需要接--with-stream,模块名叫做ngx_stream_core_module
做一个nginx的四层负载均衡
[root@lb conf]# cp nginx.conf nginx.conf.bak
[root@lb conf]# vim nginx.conf
[root@lb conf]# cat nginx.conf|egrep '^$|^#' -v
worker_processes 2;
events {
worker_connections 2048;
}
stream{
upstream web_servers{
hash $remote_addr;
server 192.168.2.33:80;
server 192.168.2.34:80;
}
server{
listen 80;
proxy_pass web_servers;
}
}
[root@lb conf]# nginx -t
nginx: the configuration file /usr/local/sclilin99/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/sclilin99/conf/nginx.conf test is successful
[root@lb conf]# nginx -s reload
[root@lb conf]# ps aux|grep nginx
root 3888 0.0 0.2 50668 2204 ? Ss 09:03 0:00 nginx: master process /usr/local/sclilin99/sbin/nginx
lilin 4649 0.0 0.2 51632 2412 ? S 10:04 0:00 nginx: worker process
lilin 4650 0.0 0.2 51632 2412 ? S 10:04 0:00 nginx: worker process
root 4652 0.0 0.0 112824 988 pts/1 R+ 10:04 0:00 grep --color=auto nginx
nginx官方的四层负载均衡举例:TCP and UDP Load Balancing | NGINX Plus
stream {
upstream stream_backend {
least_conn;
server backend1.example.com:12345 weight=5;
server backend2.example.com:12345 max_fails=2 fail_timeout=30s;
server backend3.example.com:12345 max_conns=3;
}
upstream dns_servers {
least_conn;
server 192.168.136.130:53;
server 192.168.136.131:53;
server 192.168.136.132:53;
}
server {
listen 12345;
proxy_pass stream_backend;
proxy_timeout 3s;
proxy_connect_timeout 1s;
}
server {
listen 53 udp;
proxy_pass dns_servers;
}
server {
listen 12346;
proxy_pass backend4.example.com:12346;
}
}
三层负载均衡:基于网络层,在路由器上做负载均衡,例如ospf协议可以做负载均衡,只是在中间链路上做负载均衡,不能针对具体业务做负载均衡