本文主要是介绍nginx+keepalived高可用搭建的详细步骤,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
现在有2台机器,10.5.100.36
和 10.5.100.37
,分别在这2台机器上面部署nginx和keepalived,然后利用keepalived对nginx做高可用。
1,安装好nginx,使用的是
yum install nginx -y
2,修改nginx的配置文件nginx.conf
nginx的配置文件nginx.conf
的存放地址在/etc/nginx/nginx.conf
vim /etc/nginx/nginx.conf
把以下这些内容写入nginx.conf
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并验证
启动
systemctl enable nginx
systemctl start nginx
验证
telnet 10.5.100.36 6085
telnet 10.5.100.37 6085
- 以上3个步骤分别在2台机器上实施一下。
4,Keepalived安装,以及keepalived配置文件的编写
可以采用编译安装,也可以使用yum安装。在这里我是用yum安装。并且还指定了版本号。你们想要啥版本可以去yum list keepalived
去查看一下。
yum install -y keepalived-1.3.5-19.el7.x86_64
cd /etc/keepalived
把以下内容写入/etc/keepalived/keepalived.conf
里面去
! Configuration File for keepalived
global_defs {router_id cdascript_user rootenable_script_security
}vrrp_script check_ng
{ script "/etc/keepalived/check_ng.sh"interval 2weight 2
}vrrp_instance VI_1 {#36 MASTER 37 BACKUP
state MASTER
#网关需要修改 按实际的来interface ens32virtual_router_id 36
mcast_src_ip 10.5.100.36
#权重 MASTER比BACKUP大priority 100advert_int 1authentication {auth_type PASSauth_pass 1111}
virtual_ipaddress {#虚拟IP 需要修改 主备一致10.5.100.201}track_script {check_ng}
}virtual_server 10.5.100.201 6085 {delay_loop 3lvs_sched rrlvs_method DRprotocol TCPreal_server 10.5.100.36 6085 {weight 1}
}
5, 写入/etc/keepalived/check_ng.sh
vim /etc/keepalived/check_ng.sh
把以下内容写入到/etc/keepalived/check_ng.sh
#!/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/nginxn2=`ps -C nginx --no-heading|wc -l`if [ $n2 -eq "0" ]; thenecho "$d nginx down,keepalived will stop" >> /etc/keepalived/check_ng.logsystemctl stop keepalivedfi
fi
然后再修改一下权限
chmod +x /etc/keepalived/check_ng.sh
6,启动keepalived和验证
启动
systemctl enable keepalived
systemctl start keepalived
验证
telnet 虚拟ip 6085
telnet 虚拟ip 6085
- 同样的,4,5,6三个步骤也要在两台机器分别都走一遍
这篇关于nginx+keepalived高可用搭建的详细步骤的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!