Nginx四层负载均衡:
网站发布的内容
文字 静态web-server,压缩
图片 图片服务器,缓存+CDN
视频 上传到优酷
软件四层负载均衡:
通过报文(数据包)中的目标地址和端口,加上分发机上的调度算法,决定最终选择哪个RIP。
LVS
软件七层负载均衡:
通过看客户端请求的具体内容(文字、图片、视频;网站交互)进行最终选择。
网络中常见的 SYN Flood 攻击。DOS
DDOS
要求:
版本要求,编译选项要求
nginx的版本 >=1.10
[root@nginx1 /usr/local/nginx]# ./sbin/nginx -V
nginx version: nginx/1.13.3
built by gcc 4.8.5 20150623 (Red Hat 4.8.5-36) (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 <--要这个选项
开始配置:
[root@nginx1 /usr/local/nginx]# vim conf/nginx.conf
user www;
worker_processes 1;
error_log logs/error.log;
error_log logs/error.log notice;
error_log logs/error.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
use epoll;
}
stream {
upstream tcp_ssh {
hash $remote_addr consistent;
server 172.16.0.161:22;
server 172.16.0.162:22;
}
server {
listen 24678;
proxy_connect_timeout 3s;
proxy_timeout 10s;
proxy_pass tcp_ssh;
}
}
[root@nginx1 /usr/local/nginx]# ./sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx1 /usr/local/nginx]# ./sbin/nginx -s reload
[root@nginx1 ~]# netstat -antp | grep nginx
tcp 0 0 0.0.0.0:24678 0.0.0.0:* LISTEN 929/nginx: master
访问测试:
[root@centos7-bj ~]# ssh -p 24678 [email protected]
添加数据库负载均衡
172.16.0.161 读权限
172.16.0.162 写权限
在每台节点添加对应权限的用户
161
MariaDB [(none)]> grant select on *.* to 'read'@'172.16.%' identified by '12345';
MariaDB [(none)]> flush privileges;
162
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.0.161:3306 weight=10 max_fails=3 fail_timeout=2s;
}
upstream mysql_write {
hash $remote_addr consistent;
server 172.16.0.162: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;
}
}
[root@nginx1 /usr/local/nginx]# ./sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx1 /usr/local/nginx]# ./sbin/nginx -s reload
[root@nginx1 ~]# netstat -antp | grep nginx
tcp 0 0 0.0.0.0:3307 0.0.0.0:* LISTEN 929/nginx: master
tcp 0 0 0.0.0.0:3306 0.0.0.0:* LISTEN 929/nginx: master
测试
使用其它节点测试读写权限
需要安装对应资源才能测试
[root@centos7-bj ~]# yum install -y mariadb
读权限登录(无法创建数据库)
[root@centos7-bj ~]# mysql -h 172.16.0.21 -P 3306 -u read -p
Enter password:
[root@centos7-bj ~]# mysql -h 172.16.0.21 -P 3307 -u write -p
Enter password: