Nginx自动安装配置脚本

一、Nginx介绍

Nginx 是一个流行的开源 Web 服务器软件。它最初由 Igor Sysoev 开发,并于 2004 年首次发布。 Nginx的 目标是提供高性能、高可靠性和低内存消耗的 Web服务器,同时也可以用作反向代理服务器和负载均衡器。
Nginx 以其优越的性能和高度可扩展性而闻名。相对于传统的 Web 服务器软件(如 pache),Nginx采用了一种事件驱动的架构,能够处理大量并发连接,而且在高负载下表现出色。它也具有较低的内存消耗,使得它能够高效地处理大规模的并发请求。除了作为 Web 服务器, Nginx还可以用作反向代理服务器。反向代理服务器充当客户端和后端服务器之间的中间层,接收客户端请求,并将请求转发给后端服务器。这种方式可以提供负载均衡、缓存、 SSL终端和访问控制等功能。
另外, Nginx还可以用作负载均衡器。负载均衡是将客户端请求分发到多个后端服务器上,以实现高可用性和扩展性。 Nginx 通过采用不同的负载均衡算法(如轮询、 IP哈希、最少连接等)来分配请求,确保请求在后端服务器之间均匀分布。
对于运维工作而言,如何安装 Nginx 服务器是一件非常常见的事。同时对于 Nginx 服务的配置和优化也是必不可少常态化的工作。为了提高运维工作的效率,通常会使用 Shell 脚本来完成一系列的自动化运维 服务。本实验就是通过 Shell 脚本,实现 Nginx 服务器下载、编译、安装、配置、服务管理等流程进行 统一管理。

 二、部署过程

环境要求:

1. 宿主机操作系统: Windows 11 23H2 专业版
2. 虚拟机软件: VMware Workstation 17 Pro
3. 虚拟机操作系统: openEuler-23.03 (LTS)
4. 远程连接工具: XShell 7.x
5. Nginx 源码安装程序版本: nginx-1.22.1.tar.gz

1. 配置本地仓库

首先在 /etc/yum.repo.d/ 目录下新建一个仓库文件,如: nginx.repo 。文件配置内容如下:
[baseos]
name=baseos
baseurl=/mnt
gpgcheck=0
然后将光盘挂载到 /mnt 目录下:
[root@openEuler yum.repos.d]# mount /dev/sr0 /mnt
mount: /mnt: WARNING: source write-protected, mounted read-only

2、编写脚本文件 

创建 install_nginx.sh 脚本文件进行编辑,在这个文件中先定义脚本解释器,然后再定义相关脚本使用的变量。如:
#!/bin/bash
NGINX_VERSION=1.22.1
NGINX_FILE=nginx-${NGINX_VERSION}.tar.gz
NGINX_URL=https://nginx.org/download/
NGINX_INSTALL_DIR=/opt/nginx
SRC_DIR=/usr/local/src
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`
变量说明:
1. NGINX_VERSION :定义 nginx 版本号
2. NGINX_FILE nginx 文件名
3. NGINX_URL nginx 官网地址
4. NGINX_INSTALL_DIR nginx 安装目录
5. SRC_DIR nginx 源码存放目录
6. CPUS cpu 核心数

3、加载系统版本信息  

 为了在 Shell 脚本中能够识别系统版本,并在后续定义的函数中使用,我们通过点(.)操作符来执行 /etc/os-release 文件,从而将文件中的变量加载到当前脚本执行环境中。

. /etc/os-release

4、 编写脚本提示颜色函数

为了让脚本执行时文件有颜色,我们可以在脚本中定义一个 color 函数。在这个函数中会根据成功和失败显示不同的提示信息和颜色。代码如下:
color() {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1" && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ];then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $2 = "failure" -o $2 = "1" ];then
${SETCOLOR_FAILURE}
echo -n $"FAILURE"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}

5、编写检测函数

在进行 Nginx 服务器之前,我们需要先检测是环境是否已经准备好。如果已准安装则给出提示;如果没 有安装则下载 nginx 源码包到指定目录下。同时,还需要判断是否已经挂载光盘,以及是否配置本地仓库。代码如下:
check() {
[ -e ${NGINX_INSTALL_DIR} ] && { color "Nginx has been installed, please
uninstall before installing" 1; exit; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE} ]; then
color "The installation files are ready" 0
else
color "Start downloading nginx source code" 0
wget ${NGINX_URL}${NGINX_FILE}
[ $? -ne 0 ] && { color "Failed to download ${NGINX_FILE} file" 1; exit;
}
fi
if [ $(cat /etc/yum.repos.d/*.repo | grep 'baseurl=/mnt' | wc -l) == 0 ];
then
cat > /etc/yum.repo.d/nginx.repo <<EOF
[baseos]
name=baseos
baseurl=/mnt
gpgcheck=0
EOF
color "Depository configuration successful" 0
fi
}

6、创建nginx用户

为了便于管理,我们创建一个 nginx 系统用户。在创建用户之前先对其进行判断,如果存在则不创建。 我们在 create_user 函数中创建:
create_user() {
color "Start creating nginx user" 0
if id nginx &> /dev/null; then
color "nginx user already exists" 1
else
useradd -r nginx -s /sbin/nologin
color "Successfully created nginx user" 0
fi
}

7. 安装编译环境

 对于nginx源码安装,需要有 C++ 编译环境,而由于不同的系统所需要的编译环境也不相同,因此需要根据不同的系统来进行安装。我们在 install_compilate_env 函数中实现这部分功能,代码如下:

install_compilate_env() {
color "Start installing compilation environment" 0
if [ $ID == "centos" ];then
if [[ $VERSION_ID =~ ^7 ]];then
yum -y install gcc make pcre-devel openssl-devel zlib-devel perlExtUtils-Embed
elif [[ $VERSION_ID =~ ^8 ]];then
yum -y install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel
openssl openssl-devel perl-ExtUtils-Embed
else
color "This system is not supported" 1
exit
fi
elif [ $ID == "rocky" ];then
dnf -y install gcc make gcc-c++ libtool pcre pcre-devel zlib zlib-devel
openssl openssl-devel perl-ExtUtils-Embed
elif [ $ID == "openEuler" ];then
dnf -y install gcc gcc-c++ make zlib zlib-devel openssl openssl-devel
pcre pcre-devel
else
apt update
apt -y install gcc make libpcre3 libpcre3-dev openssl libssl-dev zliblgdev
fi
[ $? -ne 0 ] && { color "Failed to install compilation environment" 1; exit;}
}

8. 配置并编译安装

 编译环境准备好后,接下来我们进入到源码下载目录,并通过解压命令对源码文件进行解压。解压成功 后,先对 nginx 进行编译配置,然后再进行编译和安装,接着再编写nginx启动服务,最后执行命令来启动Nginx。我们定义 install_nginx 函数来实现这部分功能。代码如下:

install_nginx() {
cd $SRC_DIR
tar -zxf ${NGINX_FILE}
NGINX_DIR=`echo ${NGINX_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --withhttp_ssl_module --with-http_v2_module --with-http_realip_module --withhttp_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream
--with-stream_ssl_module --with-stream_realip_module
make -j $CPUS && make install
[ $? -eq 0 ] && color "Nginx compilation and installation successful" 0 || {
color "Nginx compilation and installation failed, exiting!" 1; exit; }
}

9. 设置权限

由于 nginx 安装目录在 /opt/ 目录下,该目录只有 root 用户可以访问。为了能够让 nginx 用户可以访问该目录,需要对此目录进行权限设置。我们在 set_permission 函数中来实现。代码如下:
set_permission() {
chown -R nginx:nginx ${NGINX_INSTALL_DIR}
ln -s ${NGINX_INSTALL_DIR}/sbin/nginx /usr/local/sbin/nginx
echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
color "Permission setting successful" 0
}
在函数中我们设置了 nginx 安装目录能够被 nginx 系统用户操作,并对 nginx 可执行文件做了软链接, 同时将其写入到全局变量中。

  10、创建启动脚本

为了更好的对 nginx 服务管理,我们在 /etc/systemd/system/ 目录下新建一个名为 nginx.service 文件,在这个文件中配置 nginx 服务管理,代码如下:
config_service() {
cat > /etc/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExeStartPre=/usr/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExeStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx -c ${NGINX_INSTALL_DIR}/conf/nginx.conf
ExecReload=${NGINX_INSTALL_DIR}/sbin/nginx -s reload
ExecStop=${NGINX_INSTALL_DIR}/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
chmod +x /etc/systemd/system/nginx.service
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
systemctl is-active nginx &> /dev/null || { color "Nginx startup failed,
exit!" 1; exit; }
color "Nginx started successfully" 0
}

 在这个函数中首先创建了启动脚本,然后现给这个脚本赋予可执行权限,最后重新加载配置并加入开机启动列表。

 11、放行服务和端口

客户端如果想要访问到 nginx 服务器,还需要在防火墙中放行 HTTP 服务和相关端口,我们在
allow_access 函数中定义:
allow_access() {
firewall-cmd --permanent --add-service=http &> /dev/null
firewall-cmd --permanent --add-service=https &> /dev/null
firewall-cmd --permanent --add-port=80/tcp &> /dev/null
firewall-cmd --permanent --add-port=443/tcp &> /dev/null
firewall-cmd --reload &> /dev/null
color "Firewall release successful" 0
}

 12、编写入口函数

 为了能够将以上函数整合起来,形成一个整体,我们再定义一个 main 函数,在这个函数中分别调用执行 之前定义的函数。代码如下:

main() {
check
create_user
install_compilate_env
install_nginx
set_permission
config_service
allow_access
}
main
在函数之后,我们直接执行这个入口函数即可。

13、验证安装

打开浏览器,输入 http://你的IP地址 后,即可看到 Nginx 服务已经成功安装并运行了。

Welcome to nginx!
If you see this page, the nginx web server is successfully installed and working.
Further configuration is required.
For online documentation and support please refer to nginx.org.
Commercial support is available at nginx.com.
Thank you for using nginx

以上就完成了本章nginx自动化安装配置。

完整代码

#!/bin/bash
NGINX_VERSION=1.22.1
NGINX_FILE=nginx-${NGINX_VERSION}.tar.gz
NGINX_URL=https://nginx.org/download/
NGINX_INSTALL_DIR=/opt/nginx
SRC_DIR=/usr/local/src
CPUS=`lscpu | awk '/^CPU\(s\)/{print $2}'`
. /etc/os-release
color() {
RES_COL=60
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
SETCOLOR_FAILURE="echo -en \\033[1;31m"
SETCOLOR_WARNING="echo -en \\033[1;33m"
SETCOLOR_NORMAL="echo -en \E[0m"
echo -n "$1" && $MOVE_TO_COL
echo -n "["
if [ $2 = "success" -o $2 = "0" ];then
${SETCOLOR_SUCCESS}
echo -n $" OK "
elif [ $2 = "failure" -o $2 = "1" ];then
${SETCOLOR_FAILURE}
echo -n $"FAILURE"
else
${SETCOLOR_WARNING}
echo -n $"WARNING"
fi
${SETCOLOR_NORMAL}
echo -n "]"
echo
}
check() {
[ -e ${NGINX_INSTALL_DIR} ] && { color "Nginx has been installed, please
uninstall before installing" 1; exit; }
cd ${SRC_DIR}
if [ -e ${NGINX_FILE} ]; then
color "The installation files are ready" 0
else
color "Start downloading nginx source code" 0
wget ${NGINX_URL}${NGINX_FILE}
[ $? -ne 0 ] && { color "Failed to download ${NGINX_FILE} file" 1; exit;
}
fi
if [ $(cat /etc/yum.repos.d/*.repo | grep 'baseurl=/mnt' | wc -l) == 0 ];
then
cat > /etc/yum.repo.d/nginx.repo <<EOF
[baseos]
name=baseos
baseurl=/mnt
gpgcheck=0
EOF
color "Depository configuration successful" 0
fi
}
create_user() {
color "Start creating nginx user" 0
if id nginx &> /dev/null; then
color "nginx user already exists" 1
else
useradd -r nginx -s /sbin/nologin
color "Successfully created nginx user" 0
fi
}
install_compilate_env() {
color "Start installing compilation environment" 0
if [ $ID == "centos" ];then
if [[ $VERSION_ID =~ ^7 ]];then
yum -y install gcc make pcre-devel openssl-devel zlib-devel perlExtUtils-Embed
elif [[ $VERSION_ID =~ ^8 ]];then
yum -y install make gcc-c++ libtool pcre pcre-devel zlib zlib-devel
openssl openssl-devel perl-ExtUtils-Embed
else
color "This system is not supported" 1
exit
fi
elif [ $ID == "rocky" ];then
dnf -y install gcc make gcc-c++ libtool pcre pcre-devel zlib zlib-devel
openssl openssl-devel perl-ExtUtils-Embed
elif [ $ID == "openEuler" ];then
dnf -y install gcc gcc-c++ make zlib zlib-devel openssl openssl-devel
pcre pcre-devel
else
apt update
apt -y install gcc make libpcre3 libpcre3-dev openssl libssl-dev zliblgdev
fi
[ $? -ne 0 ] && { color "Failed to install compilation environment" 1; exit;}
}
install_nginx() {
cd $SRC_DIR
tar -zxf ${NGINX_FILE}
NGINX_DIR=`echo ${NGINX_FILE}| sed -nr 's/^(.*[0-9]).*/\1/p'`
cd ${NGINX_DIR}
./configure --prefix=${NGINX_INSTALL_DIR} --user=nginx --group=nginx --withhttp_ssl_module --with-http_v2_module --with-http_realip_module --withhttp_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream
--with-stream_ssl_module --with-stream_realip_module
make -j $CPUS && make install
[ $? -eq 0 ] && color "Nginx compilation and installation successful" 0 || {
color "Nginx compilation and installation failed, exiting!" 1; exit; }
}
set_permission() {
chown -R nginx:nginx ${NGINX_INSTALL_DIR}
ln -s ${NGINX_INSTALL_DIR}/sbin/nginx /usr/local/sbin/nginx
echo "PATH=${NGINX_INSTALL_DIR}/sbin:${PATH}" > /etc/profile.d/nginx.sh
color "Permission setting successful" 0
}
config_service() {
cat > /etc/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx server
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=${NGINX_INSTALL_DIR}/logs/nginx.pid
ExeStartPre=/usr/bin/rm -f ${NGINX_INSTALL_DIR}/logs/nginx.pid
ExeStartPre=${NGINX_INSTALL_DIR}/sbin/nginx -t
ExecStart=${NGINX_INSTALL_DIR}/sbin/nginx -c ${NGINX_INSTALL_DIR}/conf/nginx.conf
ExecReload=${NGINX_INSTALL_DIR}/sbin/nginx -s reload
ExecStop=${NGINX_INSTALL_DIR}/sbin/nginx -s quit
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
chmod +x /etc/systemd/system/nginx.service
systemctl daemon-reload
systemctl enable --now nginx &> /dev/null
systemctl is-active nginx &> /dev/null || { color "Nginx startup failed,
exit!" 1; exit; }
color "Nginx started successfully" 0
}
allow_access() {
firewall-cmd --permanent --add-service=http &> /dev/null
firewall-cmd --permanent --add-service=https &> /dev/null
firewall-cmd --permanent --add-port=80/tcp &> /dev/null
firewall-cmd --permanent --add-port=443/tcp &> /dev/null
firewall-cmd --reload &> /dev/null
color "Firewall release successful" 0
}
main() {
check
create_user
install_compilate_env
install_nginx
set_permission
config_service
allow_access
}
main

  • 13
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

左水水%

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值