nginx可以实现4层负载均衡。
软件四层负载均衡:
通过报文(数据包)中的目标地址和端口,加上分发机上的调度算法,决定最终选择哪个RIP。
LVS
软件七层负载均衡:
通过看客户端请求的具体内容(文字、图片、视频;网站交互)进行最终选择。
网络中常见的 SYN Flood 攻击。DOS。DDOS
nginx的4层负载均衡有2个条件:
1、版本在1.10以上
2、配置选项要有stream
[root@nginx-4c ~]# /usr/local/nginx/sbin/nginx -V
nginx version: nginx/1.17.6
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
built with OpenSSL 1.0.2k-fips 26 Jan 2017
TLS SNI support enabled
configure arguments: --prefix=/usr/local/nginx --user=www --group=www --with-http_stub_status_module --with-http_v2_module --with-http_ssl_module --with-http_sub_module --with-http_gzip_static_module --with-http_realip_module --with-stream
--with-stream <--要这个选项
配置:
pid logs/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
》》》》》》》》》》》》》》》》》》》》》》》》
stream {
upstream p_ssh {
hash $remote_addr consistent;
server 172.16.12.71:22;
server 172.16.12.72:22;
}
server {
listen 24678;
proxy_connect_timeout 3s;
proxy_timeout 10s;
proxy_pass p_ssh;
}
}
》》》》》》》》》》》》》》》》》》》》》》》》
然后重启服务:
查端口,有24678那个新添加的端口
[root@nginx-4c nginx]# netstat -antlup | grep nginx
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 882/nginx: master p
tcp 0 0 0.0.0.0:24678 0.0.0.0:* LISTEN 882/nginx: master p
访问测试:
[root@localhost mnt]# ssh -p 24678 root@172.16.12.82
root@172.16.12.82's password:
Last login: Sat Jan 4 00:59:11 2020 from 172.16.12.1
[root@chunk1 ~]# Connection to 172.16.12.82 closed by remote host.
Connection to 172.16.12.82 closed.
能够登录转发。
mysql
172.16.12.71
装个mysql
[root@chunk1 ~]# yum install mariadb-server -y
[root@chunk1 ~]# systemctl restart mariadb
[root@chunk1 ~]# mysql
MariaDB [(none)]> grant select on *.* to 'read'@'172.16.%' identified by '12345';
MariaDB [(none)]> flush privileges;
172.16.12.72
MariaDB [(none)]> grant all on *.* to 'write'@'172.16.%' identified by '12345';
MariaDB [(none)]> flush privileges;
stream {
upstream mysql_read {
hash $remote_addr consistent;
server 172.16.12.71:3306 weight=10 max_fails=3 fail_timeout=2s;
}
upstream mysql_write {
hash $remote_addr consistent;
server 172.16.12.72:3306 weight=10 max_fails=3 fail_timeout=2s;
}
server {
listen 3306;
proxy_connect_timeout 3s;
proxy_timeout 10s;
proxy_pass mysql_read;
}
server {
listen 3307;
proxy_connect_timeout 3s;
proxy_timeout 10s;
proxy_pass mysql_write;
}
}
重启查端口:
看到3306、3307,这两个是nginx启动的端口。
[root@nginx-4c nginx]# netstat -antlup | grep nginx
tcp 0 0 0.0.0.0:3307 0.0.0.0:* LISTEN 882/nginx: master p
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 882/nginx: master p
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 882/nginx: master p
访问测试:
[root@client ~]# yum install -y mariadb
[root@client ~]# mysql -h 172.16.12.82 -P 3306 -u read -p12345
Welcome to the MariaDB monitor. Commands end with ; or \g.
[root@client ~]# mysql -h 172.16.12.82 -P 3307 -u write -p12345
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 3
都能访问转发。ok了。