应用场景:使用Keepalived + Nginx,搭建两台(主、备)软负载服务器。
脚本功能:
1)磁盘分区,创建PV、VG、LV,磁盘格式化,文件系统挂载;
2)安装依赖包;
3)安装和配置(提前配置好的文件)Nginx、Keepalived;
4)启动相关服务;
测试环境:
1)虚拟机单独挂载了一块/dev/vdb的独立磁盘(50GB)作为数据盘,与系统盘分开;
2)系统提前挂载了在线的yum源;
3)提前准备好相关的配置文件,如:nginx.conf、keepalived.conf、chk_nginx.sh;
#! /bin/bash
####################################################
#
# Function: install nginx and keepalived
# version: 1.0
# Date: 2022/11/9
#
####################################################
echo "=============================="
PS3="chose which disk you want to create:"
select W in `ls /dev/vd*|grep -o 'vd[b-z]'|uniq` quit
do
case $W in
vda)
fdisk -l /dev/vda
break;;
vd[b-z])
echo "n
p
t
8e
w" | fdisk /dev/$W
break;;
quit)
break;;
*)
echo "Wrong disk choice, check again!";;
esac
done
pvcreate /dev/vdb1
vgcreate vg /dev/vdb1
lvcreate -L 49.9G -n data vg
mke2fs -t ext4 -b 4096 /dev/vg/data
cd /
mkdir data
mount /dev/vg/data /data
cat >> /etc/fstab << EOF
/dev/mapper/vg-data /data ext4 defaults 0 0
EOF
echo "Start to install dependent rpms by on-line yum."
yum install -y curl gcc gcc-c++ libnl libnl-devel libnl3-devel libnfnetlink-devel net-snmp-devel openssl openssl-devel patch pcre pcre-devel telnet zlib zlib-devel
nginx_version=1.22.1
keepalived_version=2.2.7
work_dir=/usr/local/src
cd $work_dir
echo "Start to install Nginx-"${nginx_version}".tar.gz"
tar -xzf ./nginx-${nginx_version}.tar.gz
rm -f ./nginx-${nginx_version}.tar.gz
echo "Start to configure and install nginx-"${nginx_version}
cd ./nginx-${nginx_version}
./configure --prefix=/data/nginx --with-threads
make
make install
cp -f $work_dir/master/nginx.conf /data/nginx/conf
cp -f $work_dir/html/403.html /data/nginx/html
cp -f $work_dir/html/404.html /data/nginx/html
mv /data/nginx/html/index.html /data/nginx/html/index_html
echo "Start to install keepalived-"${keepalived_version}".tar.gz"
mkdir -p /usr/local/keepalived /etc/keepalived
cd $work_dir
tar -xzf ./keepalived-${keepalived_version}.tar.gz
rm -f ./keepalived-${keepalived_version}.tar.gz
cd $work_dir/keepalived-${keepalived_version}
./configure --prefix=/usr/local/keepalived --sysconfdir=/etc/keepalived
make
make install
cp -f $work_dir/common/keepalived.service /usr/lib/systemd/system/
systemctl daemon-reload
systemctl enable keepalived.service
cp -f $work_dir/master/keepalived.conf /etc/keepalived/
cp -f $work_dir/common/chk_nginx.sh /etc/keepalived/
chmod u+x /etc/keepalived/chk_nginx.sh
cp $work_dir/keepalived-2.2.7/keepalived/etc/init.d/keepalived /etc/init.d
cp $work_dir/keepalived-2.2.7/keepalived/etc/sysconfig/keepalived /etc/sysconfig
cp $work_dir/keepalived-2.2.7/keepalived/etc/keepalived/keepalived.conf.sample /etc/keepalived
cp $work_dir/keepalived-2.2.7/bin/keepalived /usr/sbin
systemctl enable keepalived.service
systemctl start keepalived.service
systemctl status keepalived.service
备注:这个脚本本身并没有什么技术含量,但是通过这个脚本可以将大约三个小时(两台虚拟机)的手工安装操作时长,缩减到5至10分钟。另外,频繁的安装,确实很无聊,所以抽了点时间做成脚本。
附:Nginx软负载典型架构图