实验环境
准备四台可以互相ping通的主机,server1和server2为nginx,server3和server4作为服务器,配置好yum仓库,关闭火墙和selinux
实验思路
用keepalived来实现服务的高可用,nginx作为调度器
源码包安装nginx
tar zxf nginx-1.19.1.tar.gz
切换到解压后的安装目录执行安装命令
./configure --prefix=/usr/local/nginx --with-http_ssl_module
编译源码并安装
make && make install
安装nginx前要先设置
vim ./nginx-1.19.1/auto/cc/gcc
隐藏版本
vim ./nginx-1.19.1/src/core/nginx.h
设定安装目录
./configure --prefix=/usr/local/nginx --with-http_ssl_module
编译并且安装
make && make install
设置nginx服务文件
vim /usr/lib/systemd/system/nginx.service
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStartPre=/usr/local/nginx/sbin/nginx -t
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
创建软连接
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin/
修改nginx配置文件
vim /usr/local/nginx/conf/nginx.conf
创建nginx用户
useradd -s /sbin/nologin nginx
vim /etc/security/limits.conf
开启nginx服务
systemctl start nginx # nginx用的是80端口,开启时要关闭httpd服务
测试
关闭一个服务器的httpd
ps aux
配置keepalived文件
vim /etc/keepalived/keepalived.conf
编写keepalived和nginx绑定脚本
vim /opt/check_nginx.sh
#!/bin/bash
[ -f "/usr/local/nginx/logs/nginx.pid" ] || systemctl stop keepalived
chmod +x /opt/check_nginx.sh
启动keepalived服务
systemctl start keepalived
在另一台nginx主机进行配置
yum install keepalived -y
# 将配置好的文件发送
scp /etc/keepalived/keepalived.conf server2:/etc/keepalived
scp -r /usr/local/nginx server2:/usr/local
scp /usr/lib/systemd/system/nginx.service server2:/usr/lib/systemd/system
scp /opt/check_nginx.sh server2:/opt
在另一台nginx创建软连接,建立用户,并且配置
ln -s /usr/local/nginx/sbin/nginx /usr/local/sbin
useradd -s /sbin/nologin nginx
vim /etc/security/limits.conf
开启服务
systemctl start nginx
systemctl start keepalived
测试:
当一台nginx挂掉,它的keepalived也会被脚本关闭,另一台nginx会接管资源,继续调度运行
关闭一台nginx,可以正常运行