s-blog

Shell 脚本:自动部署 Nginx

ssssmy · 2026-06-05 · 2 min · Linux

把手动编译部署 Nginx 的步骤写成 shell 脚本。安装路径:/usr/local/nginx/sbin/nginx、配置 /usr/local/nginx/conf/nginx.conf

手动部署步骤

# 1) 下载源码
cd /usr/local/src
sudo curl -O http://nginx.org/download/nginx-1.23.0.tar.gz

# 2) 解压
sudo tar zxf nginx-1.23.0.tar.gz
cd nginx-1.23.0

# 3) 安装依赖(RHEL/Rocky)
sudo yum install -y gcc make pcre-devel zlib-devel openssl-devel

# 4) 配置
sudo ./configure --prefix=/usr/local/nginx --with-http_ssl_module

# 5) 编译安装
sudo make && sudo make install

systemd 服务管理脚本

/lib/systemd/system/nginx.service

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP $(/bin/cat /usr/local/nginx/logs/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM $(/bin/cat /usr/local/nginx/logs/nginx.pid)"

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl start nginx

把以上步骤写进 #!/bin/bash 脚本,每步后用 if [ $? -ne 0 ]; then echo error; exit 1; fi 做错误检查即可一键部署。

原文链接:https://www.ssssmy.com/notes/shell-jiao-ben-zi-dong-bu-shu-nginx