目录
一.安装nginx
1.安装linux7.6,部署虚拟机,selinux和firewalld都要禁掉
2.访问nginx.org,下载1.22.0,一定是稳定版https://nginx.org/en/download.html
3.配置7.6的yum源
配置7.6的yum源
[dvd]
name=rhel7.6
baseurl=file:///media
gpgcheck=0
4.解压1.22.0的tar包
tar zxf nginx-1.22.0.tar.gz
ls
cd nginx-1.22.0
5.安装
yum install -y gcc pcre-devel openssl-devel 安装gcc pcre库 openssl库
在REDHAT系统上,提示缺少xx库,就在xx后加-devel(开发包,REDHAT的开发包单独存放的)
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module(在nginx-1.22.0目录下)
源码编译三步曲:(在同一层路径)
1.configure完成后会在同目录下胜场makefile
2.make 根据makefile的定义,编译出需要的二进制程序(在objs里)
3.make install 编译安装,把编译好的二进制程序复制到指定路径
二.nginx的负载均衡
1.实验环境的部署:开启三台虚拟机,禁掉防火墙和selinux,配置好网络,配置好yum源,安装httpd,设置httpd为开机自启
在cd /var/www/html下放一个测试页看是否能访问
cd /var/www/html
ls
echo web2 > index.html
curl localhost
2.负载均衡的实现:
cd /usr/local/nginx/
cd conf/在此目录编译,在源码路径编译没有用
vim nginx.conf
nginx -t 检测语法
nginx -s reload 重载配置
3.在外部访问
for循环查看:for i in {1..10}; do curl 192.168.155.20; done
4.负载均衡的权重
三.nginx的并发优化
1.修改配置
cd /etc/pam.d/
vim /etc/security/limits.conf pam热插拔模块即改即生效
useradd -M -d /usr/local/nginx -s /sbin/nologin nginx
cd /usr/local/nginx/
cd conf/在此目录编译,在源码路径编译没有用
vim nginx.conf
user nginx nginx;
worker_processes 2;
worker_cpu_affinity 01 10;静态绑定,
use epoll; //默认使用epoll模型
worker_connections 65535; 并发连接数是65535
2. nginx -s reload重载配置
ps ax 查看
4.编辑vim/usr/local/nginx/conf/nginx.conf
停掉22的httpd
如果客户端和服务器端直接连接,可以通过ip_hash负载均衡,如果有代理(cdn),通过cookie来负载均衡。
ip_hash会根据客户端来源IP来判断,如果所有的请求都是来自于同一个IP客户端发来的,就会把他调度到同一个后端,也就不会负载均衡。ip_hash可以实现同一个客户端放同一个后端,只要ip不变。ip_hash的局限性,正常浏览器的访问会经过cdn,加速(相当于代理,nginx),客户端通过cdn之后,相当于经过代理,之后所有的源地址变成cdn的ip,对于后端服务器来说,如果还是通过经过ip_hash算法来调度的话,会把请求交给同一个后端。
每个用户的浏览器可以做标记,session存在服务器端,cookie存在客户端浏览器,当用户和后端服务器建立连接之后,后端服务器会给一个cookie信息,浏览器根据cook来负载均衡,均衡力度更高。
5.下载第三方插件sticky模块,解压
nginx -s stop
unzip nginx-goodies-nginx-sticky-module-ng-08a395c66e42.zip
ls
cd nginx-1.22.0/
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-
http_stub_status_module --add-module=/root/nginx-goodies-nginx-sticky-module-ng-
08a395c66e42
make 编译,不用make install,因为程序之前已经装好了,现在只是更新,
会把模块静态编译到cd nginx-1.22.0/objs/下的nginx
cd /usr/local/nginx/conf
vim nginx.conf
nginx -t
nginx
在外部浏览器访问;