现在有2台机器,10.5.100.36
和 10.5.100.37
,分别在这2台机器上面部署nginx和keepalived,然后利用keepalived对nginx做高可用。
1,安装好nginx,使用的是
bash
yum install nginx -y
2,修改nginx的配置文件nginx.conf
nginx的配置文件nginx.conf
的存放地址在/etc/nginx/nginx.conf
bash
vim /etc/nginx/nginx.conf
把以下这些内容写入nginx.conf
bash
user root;
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;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
keepalive_timeout 120s;
gzip on;
#cda服务
upstream cda_server{
server 10.5.100.36:8099 weight=1 max_fails=3 fail_timeout=10;
server 10.5.100.37:8099 weight=1 max_fails=3 fail_timeout=10;
}
server {
#nginx端口
listen 6085;
server_name localhost;
client_max_body_size 20m;
location / {
proxy_pass http://cda_server;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
}
}
}
3,启动nginx并验证
启动
bash
systemctl enable nginx
systemctl start nginx
验证
bash
telnet 10.5.100.36 6085
telnet 10.5.100.37 6085
- 以上3个步骤分别在2台机器上实施一下。
4,Keepalived安装,以及keepalived配置文件的编写
可以采用编译安装,也可以使用yum安装。在这里我是用yum安装。并且还指定了版本号。你们想要啥版本可以去yum list keepalived
去查看一下。
bash
yum install -y keepalived-1.3.5-19.el7.x86_64
bash
cd /etc/keepalived
把以下内容写入/etc/keepalived/keepalived.conf
里面去
bash
! Configuration File for keepalived
global_defs {
router_id cda
script_user root
enable_script_security
}
vrrp_script check_ng
{
script "/etc/keepalived/check_ng.sh"
interval 2
weight 2
}
vrrp_instance VI_1 {
#36 MASTER 37 BACKUP
state MASTER
#网关需要修改 按实际的来
interface ens32
virtual_router_id 36
mcast_src_ip 10.5.100.36
#权重 MASTER比BACKUP大
priority 100
advert_int 1
authentication {
auth_type PASS
auth_pass 1111
}
virtual_ipaddress {
#虚拟IP 需要修改 主备一致
10.5.100.201
}
track_script {
check_ng
}
}
virtual_server 10.5.100.201 6085 {
delay_loop 3
lvs_sched rr
lvs_method DR
protocol TCP
real_server 10.5.100.36 6085 {
weight 1
}
}
5, 写入/etc/keepalived/check_ng.sh
bash
vim /etc/keepalived/check_ng.sh
把以下内容写入到/etc/keepalived/check_ng.sh
bash
#!/bin/bash
#时间变量,用于记录日志
d=`date --date today +%Y%m%d_%H:%M:%S`
#计算nginx进程数量
n=`ps -C nginx --no-heading|wc -l`
#如果进程为0,则启动nginx,并且再次检测nginx进程数量,
#如果还为0,说明nginx无法启动,此时需要关闭keepalived
if [ $n -eq "0" ]; then
/usr/local/nginx/sbin/nginx
n2=`ps -C nginx --no-heading|wc -l`
if [ $n2 -eq "0" ]; then
echo "$d nginx down,keepalived will stop" >> /etc/keepalived/check_ng.log
systemctl stop keepalived
fi
fi
然后再修改一下权限
bash
chmod +x /etc/keepalived/check_ng.sh
6,启动keepalived和验证
启动
bash
systemctl enable keepalived
systemctl start keepalived
验证
bash
telnet 虚拟ip 6085
telnet 虚拟ip 6085
- 同样的,4,5,6三个步骤也要在两台机器分别都走一遍