最近公司重整架构,老板给出十几台左右的服务器而且还要尽可能节约成本我就谷歌了一下在几种集群之前进行比较最终采用了Keepalived+Nginx做负债均衡高可用。虽然之前也研究过集群,看过很多集群方面的原理和架构,但毕竟没有真正操作过以下案例是在虚拟机中完成实验其实对于高可用搭建来说只用给出Keepalived和Nginx的配置即可后面的一些安装搭建完全是本人项目需要可以不用理睬仅供参考。
本文只是实验搭建记录方便以后在服务器中实施搭建。
架构图如下
前提介绍本案例采用Centos7+Keepalived1.3.5+Tomcat9+Mysql5.6+Redis3.2.8+Rabbitmq3.6.10
一、集群搭建DR模式
前端LVS采用主从模式,Nginx为后端realserver负债均衡。
服务器环境如下
nginx+LVS_master | 192.168.23.14 |
nginx+LVS_backup | 192.168.23.15 |
VIP | 192.168.23.20 |
Tomcat | 192.168.23.16 ;192.168.23.17 ;192.168.23.18 |
redis | 192.168.23.21 |
Mysql | 192.168.23.22 |
1、安装前调试以及优化
安装centos7选择默认最小化
停止firewalld运行
systemctl stop firewalld.service systemctl disable firewalld.service
内核优化vi/etc/sysctl.conf
##关闭ipv6 net.ipv6.conf.all.disable_ipv6 = 1 net.ipv6.conf.default.disable_ipv6 = 1 ##路由转发n et.ipv4.ip_forward = 1 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0
防火墙安装iptables
yum -y install iptables-services iptables
修改selinux
vi/etc/selinux/config 修改selinux为disabled
重启
reboot
2、安装master和backup
安装前准备
yum -y install openssl openssl-devel popt popt-devel gcc* wget vim ipvsadm pcre pcre-devel
运行ipvsadm
查看内核模块是否存在
lsmod|grep ip_vs
建立data目录
makdir /data
下载安装
wget tar zxfkeepalived-1.3.5.tar.gz -C /data ./configure --prefix=/usr/local/keepalived-1.3.5 make && make install
复制keepalived文件和脚本
cp/usr/local/keepalived-1.3.5/sbin/keepalived /usr/sbin/ cp/usr/local/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/ cp/usr/local/keepalived/etc/sysconfig/keepalived /etc/sysconfig/ cp/data/keepalived-1.3.5/./keepalived/etc/init.d/keepalived /etc/init.d/ chmod 755/etc/init.d/keepalived mkdir/etc/keepalived/
配置lvs网卡设置下的vip
#!/bin/bash # description: Config realserver lo and apply noarp # chkconfig: 345 80 20 SNS_VIP0=192.168.23.20 . /etc/rc.d/init.d/functions case "$1" in start) /sbin/ifconfig ens37 down /sbin/ifconfig ens37 up echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce ifconfig ens37:0 $SNS_VIP0 netmask 255.255.255.255 broadcast $SNS_VIP0 up /sbin/route add -host $SNS_VIP0 dev ens37:0 echo "RealServer Start OK" ;; stop) ifconfig ens37:0 down route del $SNS_VIP0 >/dev/null 2>&1 echo "0" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "0" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/all/arp_announce echo "RealServer Stoped" ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0
重启网卡
systemctl restart network.service
设置开启启动
chkconfig --add keepalived chkconfig --level 345 keepalived on
设置master /etc/keepalived/文件
! Configuration File for keepalived global_defs { #lvs组设置 router_id LVS1 #id_唯一标识 } vrrp_instance VI_1 { #vrrp设置,VI_1自定义名称 state MASTER #master设置,必须大写 interface ens33 #网卡设置,绑定vip的子接口,lvs需要绑定在网卡上,realserver绑定在回环口。区别:lvs对访问为外,realserver为内不易暴露本机信息。 virtual_router_id 51 #router_id,vrrp唯一标识,一致 priority 100 #优先级,越大越优先 advert_int 1 #组播信息发送间隔,两个节点设置必须一样 authentication { #设置验证信息,两个节点必须一致 auth_type PASS auth_pass lmnginx } virtual_ipaddress { #设置vip 192.168.23.20 } } virtual_server 192.168.23.20 80 { #设置vip连接下的realserver delay_loop 1 #每1秒检测回环口 lb_algo rr #设置调度算法为默认rr轮询 lb_kind DR #设置lvs默认为DR直接路由模式。建议lvs都是内网ip部署,最后vip用路由器映射到外网,最为安全! protocol TCP #启用TCP检测模式 real_server 192.168.23.14 80 { #realserver的ip地址 weight 1 #权重,最大越高,lvs就越优先访问。 TCP_CHECK { #TCP模式检测后端连接 connect_timeout 3 #超时3秒 retry 2 #重连次数2次 delay_before_retry 3 #重连间隔时间3秒 connect_port 80 #检测后端realserver的端口 } } real_server 192.168.23.15 80 { weight 1 TCP_CHECK { connect_timeout 3 retry 3 delay_before_retry 3 connect_port 80 } } }
设置backup /etc/keepalived/文件
! Configuration File for keepalived global_defs { router_id LVS2 } vrrp_instance VI_1 { state BACKUP interface ens33 virtual_router_id 51 priority 80 advert_int 1 authentication { auth_type PASS auth_pass lmnginx #与backup的认证密码 } virtual_ipaddress { 192.168.23.20 } } virtual_server 192.168.23.20 80 { delay_loop 1 lb_algo rr lb_kind DR protocol TCP real_server 192.168.23.14 80 { weight 1 TCP_CHECK { connect_timeout 3 retry 2 delay_before_retry 3 connect_port 80 } } real_server 192.168.23.15 80 { weight 1 TCP_CHECK { connect_timeout 3 retry 3 delay_before_retry 3 connect_port 80 } } }
nginx监控脚本
#!/bin/bash ip=`ifconfig ens33 |grep "inet" |awk -F " " '{print $2}'` nginx=`ps -C nginx --no-header |wc -l` date=`date +%F-%r` while true do if [ $nginx -eq 0 ]; then killall keepalived echo "$date $ip nginx宕机" |/bin/mail -s "$ip" [email protected] >/dev/null 2>&1 fi sleep 1h done
sleep 1h 设置每小时发送一次while ture执行正确为止后退出使用后台运行
nohup ./nginx >/dev/null 2>&1 &
附mail设置
安装mail
yum -y install mailx
设置mail文件
vim /etc/mail.rc set from=***@163.com你的邮箱名建议和账号一致 smtp=smtp.163.com 邮箱的stmp服务器 set smtp-auth-user=***@163.com你的邮箱账号 smtp-auth-password=password你的邮箱密码这个密码是stmp认证用户的密码不懂可以百度 smtp-auth=login 确定登陆
3、nginx编译安装
安装依赖包
yum install -y vim wget lsof gcc gcc-c++ bzip2 net-tools bind-utilszlib-devel openssl-devel libxml2-devel libxslt-devel perl-devel perl-ExtUtils-Embed
创建nginx用户
groupadd nginx useradd -s /sbin/nologin -g nginx -M nginx
安装Pcre
下载 wget http://www.pcre.org/pcre-8.41.tar.gz
cd /data tar zxf pcre.tar.gz ./configure --prefix=/usr/local/pcre &&make && make install
安装openssl
下载安装
wget https://www.openssl.org/source/openssl-1.1.0f.tar.gz cd /data tar zxf openssl.tar.gz ./config --prefix=/usr/local/openssl &&make && make install
安装zlib
下载安装
wget www.zlib.net/zlib-1.2.11.tar.gz cd /data tar zxf zlib.tar.gz ./configure --prefix=/usr/local/zlib &&make && make install
创建目录
mkdir -p /var/tmp/nginx/{client,proxy,fastcgi,uwsgi,scgi} mkdir /var/log/nginx mkdir /etc/nginx
安装nginx
下载安装
wget ./configure --prefix=/usr/local/nginx--sbin-path=/usr/sbin/nginx --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx/error.log --http-log-path=/var/log/nginx/access.log --lock-path=/var/lock/nginx.lock--user=nginx --group=nginx --with-http_ssl_module --with-http_dav_module --with-http_flv_module --with-http_realip_module --with-http_addition_module --with-http_xslt_module --with-http_stub_status_module --with-http_sub_module --with-http_random_index_module --with-http_degradation_module --with-http_secure_link_module --with-http_gzip_static_module --with-http_perl_module --with-http_v2_module --with-threads --with-stream--with-stream_ssl_module --with-pcre=/data/pcre=8.41.n"sp; --with-zlib=/data/zlib-1.2.11 --with-openssl=/data/openssl-1.1.0f --with-file-aio --with-mail --with-mail_ssl_module --http-client-body-temp-path=/var/tmp/nginx/client_body --http-proxy-temp-path=/var/tmp/nginx/proxy --http-fastcgi-temp-path=/var/tmp/nginx/fastcgi --http-uwsgi-temp-path=/var/tmp/nginx/uwsgi --http-scgi-temp-path=/var/tmp/nginx/scgi --with-ld-opt="-Wl,-E" make && make install
配置realserver回环口下的的vip
#!/bin/bash # description: Config realserver lo and apply noarp # chkconfig: 345 80 20 SNS_VIP0=192.168.23.20 . /etc/rc.d/init.d/functions case "$1" in start) /sbin/ifconfig lo down /sbin/ifconfig lo up echo "1" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "1" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "2" >/proc/sys/net/ipv4/conf/all/arp_announce ifconfig lo:0 $SNS_VIP0 netmask 255.255.255.255 broadcast $SNS_VIP0 up /sbin/route add -host $SNS_VIP0 dev lo:0 echo "RealServer Start OK" ;; stop) ifconfig lo:0 down route del $SNS_VIP0 >/dev/null 2>&1 echo "0" >/proc/sys/net/ipv4/conf/lo/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/lo/arp_announce echo "0" >/proc/sys/net/ipv4/conf/all/arp_ignore echo "0" >/proc/sys/net/ipv4/conf/all/arp_announce echo "RealServer Stoped" ;; *) echo "Usage: $0 {start|stop}" exit 1 esac exit 0
配置nginx
实现静动分离和负债均衡
user nginx; worker_processes auto; events { worker_connections 65535; #使用epoll模块增强性能 use epoll; #打开文件描述符(缓存有用) multi_accept on; } http { #隐藏nginx版本号 server_tokens off; #指定nginx配置的软链接 include mime.types; include conf.d/*; #默认文件类型 default_type text/html; #日志格式默认 log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for" "$request_time"'; #开启高效的文件传输模式 sendfile on; #连接超时后重置连接,减少等待 reset_timedout_connection off; #限制连接,zone自定义 limit_conn_zone $binary_remote_addr zone=addr:5m; #限制连接数每个用户最大打开100次 limit_conn addr 100; #默认一个一个发,这里为发送所以头部文件 tcp_nopush on; #不缓存数据 tcp_nodelay on; #字符集 charset UTF-8; #连接超时(秒) keepalive_timeout 65; #开启压缩 gzip on; gzip_proxied any; gzip_min_length 1000; gzip_comp_level 4; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; #设置访问头部 proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; #设置缓存 client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 75; proxy_read_timeout 300; proxy_send_timeout 300; proxy_buffer_size 16k; proxy_buffers 4 64k; proxy_busy_buffers_size 128k; proxy_temp_file_write_size 128k; proxy_temp_path /data/temp_path; proxy_cache_path /data/cache_path levels=1:2 keys_zone=cache_one:200m inactive=5d max_size=30g; #设置负债均衡 upstream www.limeng.com { server 192.168.23.16; server 192.168.23.17; server 192.168.23.18; #设置nginx连接tomcat之间得连接为长连接。此设置默认关闭,导致nginx与tomcat得time_wait短暂,造成资源浪费,keepalive默认单位秒,官方建议16不可大不可小。 keepalive 16 } server { listen 80; server_name limeng; index index.html index.htm index.jsp index.do; #默认代理本机默认页面 location / { proxy_pass http://www.limeng.com; } #设置缓存策略 location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css)$ { root /usr/local/nginx/ROOT; if (-f $request_filename) { expires 1d; break; } proxy_cache_key '$host:$server_port$request_uri';#缓存服务和路径 proxy_redirect off; proxy_cache cache_one;#缓存的zone名 proxy_cache_valid 200 302 1h; #缓存200和302时间1小时 proxy_cache_valid 301 1d;#缓存301时间为1天 proxy_cache_valid any 1m; #其他缓存为1个月 expires 7d; } #设置其他未缓存策略 location ~ .*$(jsp|do) { #设置长连接策略,nginx默认为http1.0,而tomcat默认为http1.1 。 proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://www.limeng.com if (-f $request_filename) { expires 1d; break; } } #禁止nginx访问tomcat的关键目录 location ~ ^/(WEB-INF|META-INF)/{ deny all; } #默认的访问代码 error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
注俩台nginx配置一样
nginx启动脚本自行谷歌
chmod 755 /etc/init.d/nginx
启动nginx
/etc/init.d/nginx start
Nginx安装完成
4、后端web服务器Tomcat安装
jdk安装
安装前准备
yum -y install gcc*wget vim
检查命令
java -version java -version
卸载
rpm -e --nodeps jdk
解压安装
wget http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1502180263_4da80e17ef2af74cdbd6c02a779d1db6 tar -zxvf jdk-8u144-linux-x64.tar.gz
移动目录
mv ./jdk1.8.0_121/usr/local/java/
最后再删除安装文件
rm -rf jdk-8u144-linux-x64.gz
配置环境变量
vi /etc/profile加入以下变量 exportJAVA_HOME=/usr/local/java/ exportCLASSPATH=.:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar exportPATH=$PATH:$JAVA_HOME/bin
加载变量
source /etc/profile
tomcat安装
解压
wget http://mirror.bit.edu.cn/apache/tomcat/tomcat-9/v9.0.0.M22/bin/apache-tomcat-9.0.0.M18.tar.gz tar -zxvf apache-tomcat-9.0.0.M18.tar.gz
解压完整后删除安装包
rm -rf apache-tomcat-9.0.0.M18.tar.gz
移动目录
mkdir /usr/local/tomcat/ mv ./apache-tomcat-9.0.0.M18//usr/local/tomcat/
首先我们来配置一下tomcat的环境变量和内存设置进入tomcat的bin目录后通过vim命令打开catalina.sh文件并在其中加入如下配置>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
xms:初始化内存。
xmx:最大内存,一般为物理机的1/4。(和xms一样为了防止内存溢出)
xmn:tomcat最小内存,一般为xmn的一半的值。
JAVA_OPTS="-Dfile.encoding=UTF-8 -server -Xms1024m -Xmx1024m -Xmn512m -XX:SurvivorRatio=10 -XX:MaxTenuringThreshold=15 -XX:NewRatio=2 -XX:+DisableExplicitGC" export TOMCAT_HOME=/tmp/tomcat/apache-tomcat-9.0.0.M18 export CATALINA_HOME=/tmp/tomcat/apache-tomcat-9.0.0.M18 export JRE_HOME=/tmp/java/jdk1.8.0_121 export JAVA_HOME=/tmp/java/jdk1.8.0_121
server.xml优化配置 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
maxThreads:tomcat最大线程组。
minSpareThreads:tomcat初始线程值。
maxSpareThreads:tomcat空闲线程,超过这个线程将关闭无用线程值。
acceptCount:当所有可以使用的处理请求的线程数都被使用时,可以放到处理队列中的请求数,超过这个数的请求将不予处理。
启动
./startup.sh
5、mysql安装配置
安装前准备
yum -y install makegcc cmake bison-devel ncurses-devel libaio libaio-devel per-Data-Dumpernet-tools gcc* wget vim autoconf
查看是否有mysql的rpm包
rpm -qa |grep mysql rpm -e --nodeps mysql
查看是否有mariadb-libs的rpm包
rpm -qa |grep mariadb-libs yum -y install mariadb-libs
解压文件
wget https://www.mysql.com/downloads/mysql-5.6.23.tar.gz tar -zxf /data/mysql-5.6.23.tar.gz
编译安装
cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql -DMYSQL_DATADIR=/usr/local/mysql/data -DSYSCONFDIR=/etc -DWITH_MYISAM_STORAGE_ENGINE=1 -DWITH_INNOBASE_STORAGE_ENGINE=1 -DWITH_MEMORY_STORAGE_ENGINE=1 -DWITH_READLINE=1 -DMYSQL_UNIX_ADDR=/var/lib/mysql/mysql.sock -DMYSQL_TCP_PORT=3306 -DENABLED_LOCAL_INFILE=1 -DWITH_PARTITION_STORAGE_ENGINE=1 -DEXTRA_CHARSETS=all -DDEFAULT_CHARSET=utf8 -DDEFAULT_COLLATION=utf8_general_ci make &&make install
建立用户和组
groupadd mysql useradd mysql -s/sbin/nologin -g mysql
给权限
chown -Rmysql:mysql /usr/local/mysql/
mysql下的初始化
/usr/local/mysql/scripts/mysql_install_db--user=mysql --basedir=/usr/local/mysql/
拷贝配置文件my.cnf
cd support-files/ cp my-default.cnf /etc/my.cnf
配置mysql
[client] port=3306 socket=/var/lib/mysql/mysql.sock #socket线程,建议设置,如果设置为默认,意外重启后可能会报错。 [mysql] no-auto-rehash #启动条件,优化启动时间。 [mysqld] user=mysql port=3306 basedir=/usr/local/mysql #mysql主目录 datadir=/var/lib/mysql #mysql数据目录 open_files_limit=10240 #打开文件数 back_log=600 #TCP/IP连接监听队列大小,默认80 max_connections = 3000 #最大进程连接数,默认151 external-locking = FALSE #避免外部锁定,默认开启 max_allowed_packet = 32M #设置网络传输一次消息的最大,默认为4M thread_cache_size = 300 #配置服务器线程的缓存值,为M key_buffer_size = 2048M #批定用于索引的缓冲区大小 read_rnd_buffer_size = 16M #MySql的随机读(查询操作)缓冲区大小,尽量适当设置该值,以避免内存开销过大 bulk_insert_buffer_size = 64M #批量插入数据缓存大小,默认为8M innodb_buffer_pool_size = 2048M #这对Innodb表来说非常重要,设置它高达 70-80% 的可用内存。 skip-name-resolve #跳过域名 #skip-innodb #不使用innodb引擎,5.5默认使用innodb,性能优越。 # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 # Settings user and group are ignored when systemd is used. # If&n`sp;xou need to run mysqld under a different user or group, # customize your systemd unit file for mariadb according to the # instructions in http://fedoraproject.org/wiki/Systemd [mysqld_safe] log-error=/var/log/mysql_error.log pid-file=/var/run/mysql/mysql.pid # # include all files from the config directory # !includedir /etc/my.cnf.d
添加变量
echo "exportPATH=$PATH:/usr/local/mysql/bin" >> /etc/profile source /etc/profile
添加开机启动
cp/usr/local/mysql/./support-files/mysql.server /etc/rc.d/init.d/mysqld chmod +x/etc/init.d/mysqld chkconfig --addmysqld chkconfig mysqld on
启动mysql
systemctl startmysqld.service
查看端口
netstat -anpt |grepmysql
编辑etc下的my.cnf文件
设置mysql密码
mysqladmin -uroot password
六、redis安装
解压安装
wget https://redis.io/download/redis-3.2.8.tar.gz tar -zxf /data/redis-3.2.8.tar.gz cd redis-3.2.8 make PREFIX=/usr/local/redis install
执行完进入目录/usr/local/redis
建立文件夹并拷贝
mkdir /etc/redis cp -rf /data/redis-3.2.8/redis.conf /etc/6379.conf
编辑配置文件vim/etc/redis/6379.conf
daemonize yes bind 192.168.23.21 127.0.0.1 (链接ip和本地 logfile "/var/log/redis.log"(自定义) databases 16 (默认数据库数量 dbfilename dump.rdb 默认存储名 dir/tmp/redis/data/redisdata 默认数据存放目录 requirepass password (自己设置redis的密码)
启动redis
./redis_server /usr/local/redis/redis.conf
七、rabbitmq安装
安装前准备
yum -y install makegcc gcc-c++ kernel-devel m4 ncurses-devel openssl-devel
解压 zlang
tar -zxf /data/otp_src_19.3.tar.gz cd otp_src_19.3
编译安装
./configure --prefix=/usr/local/erlang --with-ssl -enable-threads -enable-smmp-support -enable-kernel-poll --enable-hipe --without -javac make && make install
安装rtabbitmq
wget 鑤tp:o/wuw.rabbitmq.com/download.html/rabbitmq-server-generic-unix-3.6.10.tar.xz tar -xf rabbitmq-server-generic-unix-3.6.10.tar.xz
移动位置
mv rabbitmq_server-3.6.10/ /usr/local/rabbitmq-3.6.10/ cd rabbitmq-3.6.10/sbin
启动rabbitmq
./rabbitmq-plugins enabler abbitmq_management ./rabbitmq-server -detached后台启动
停止
./rabbitmqctl stop
查看程序和端口运行状态
ps aux |grep rabbitmq netstat -anpt |grep 15672
添加账户并设置为管理员
./rabbitmqctl add_user admin password ./rabbitmq set_tagsadmin administrator
删除默认用户guest
./rabbitmqctl delete_user guest
查看设置用户是否存在
./rabbitmqctl list_users
二、测试集群
在界面打开浏览器测试访问192.168.23.20如下
期间不断的刷新会出现不同的后端web页面。
关闭master测试访问正常backup接替工作
systemctl stop keepalived