1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/bin/bash
. /etc/init.d/functions

PackageDir="/root"
PackageName="nginx-1.18.0"
SUFFIX='tar.gz'
PACKAGE_INSTALL_DIR="/apps/nginx"
PackageURL=https://nginx.org/download/nginx-1.18.0.tar.gz
PIDFileDIR=/apps/nginx/run
CPU_CORE=`lscpu | awk '/^CPU\(s\)/ {print $2}'`

# 创建登录用户
if ! id nginx &> /dev/null;then
useradd -r -s /sbin/nologin nginx
fi

# 创建安装目录
if [ -d ${PACKAGE_INSTALL_DIR} ];then
action "nginx已经安装,退出安装" /bin/false
exit 1
else
mkdir -p ${PACKAGE_INSTALL_DIR} || { echo -e "\033[1;31m${PACKAGE_INSTALL_DIR} 安装目录创建失败\033[0m";exit 1; }
fi

# 安装相关依赖包
echo -e "\033[1;32m正在安装相关依赖包...\033[0m"
yum -y install gcc pcre-devel openssl-devel zlib-devel wget &> /dev/null || { echo -e "\033[1;31minstall package fail\033[0m";exit 1; }

# 准备nginx 1.8 源码包
if ! [ -e ${PackageDir}/${PackageName}.${SUFFIX} ];then
echo -e "\033[1;31m${PackageName}.${SUFFIX} file is not exits, will online download...\033[0m"
wget -P ${PackageDir} ${PackageURL} || { echo -e "\033[1;31mFile download fail\033[0m";exit 1; }
fi

# 准备安装
action "Start compiling and installing Nginx1.8" /bin/true
tar xf ${PackageDir}/${PackageName}.${SUFFIX} -C /usr/local/

cd /usr/local/${PackageName}
./configure --prefix=${PACKAGE_INSTALL_DIR} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module

make -j ${CPU_CORE} || { echo -e "\033[1;31m编译失败\033[0m";exit 1; }
make install && echo -e "\033[1;32m编译安装成功\033[0m" || { echo -e "\033[1;31m编译安装失败\033[0m";exit 1; }


# 修改权限
chown -R nginx:nginx ${PACKAGE_INSTALL_DIR}

# 创建软连接
ln -s ${PACKAGE_INSTALL_DIR}/sbin/nginx /usr/sbin


# 配置Nginx自启动文件
cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=The nginx HTTP and reverse proxy server
After=network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=${PIDFileDIR}/nginx.pid
ExecStartPre=/usr/bin/rm -f ${PIDFileDIR}/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP \$MAINPID
KillSignal=SIGQUIT
TimeoutStopSec=5
KillMode=mixed
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

# 修改配置文件
sed -Ei.bak -e "/pid/s@.*@pid ${PIDFileDIR}/nginx.pid;@" -e "/\<worker_processes\>/s@.*@worker_processes ${CPU_CORE};@" ${PACKAGE_INSTALL_DIR}/conf/nginx.conf


# 创建进程目录
mkdir -p ${PIDFileDIR}

systemctl daemon-reload &> /dev/null
systemctl enable --now nginx &> /dev/null || { echo -e "\033[1;31mNginx server start Fail\033[0m";exit 1; }

action "Nginx server started success" /bin/true