1. Shell脚本与Nginx一键部署实战指南
在Linux系统管理和Web服务部署中,Shell脚本的价值怎么强调都不为过。最近在帮朋友部署Web服务时,我再次体会到写好Shell脚本能节省多少重复劳动。今天就来分享一个经过实战检验的Nginx一键部署脚本,这个方案已经在超过20台生产服务器上稳定运行了三年。
2. 环境准备与基础配置
2.1 系统环境检查
在开始部署前,我们需要确认基础环境是否符合要求。这个脚本适配CentOS 7/8和Ubuntu 18.04/20.04主流版本,建议使用干净的系统环境。
#!/bin/bash # 检查系统版本 if [ -f /etc/redhat-release ]; then OS="centos" OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release) elif [ -f /etc/lsb-release ]; then OS="ubuntu" OS_VERSION=$(grep DISTRIB_RELEASE /etc/lsb-release | cut -d= -f2) else echo "不支持的Linux发行版" exit 1 fi注意:不同Linux发行版的包管理命令和配置文件路径可能不同,脚本中需要做好分支判断。
2.2 依赖包安装
Nginx编译安装需要一些基础开发工具和库文件,以下是自动安装依赖的逻辑:
install_dependencies() { echo "正在安装依赖包..." if [ "$OS" = "centos" ]; then yum install -y gcc make pcre-devel zlib-devel openssl-devel wget else apt-get update apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g-dev libssl-dev wget fi [ $? -ne 0 ] && echo "依赖安装失败" && exit 1 }3. Nginx安装与配置
3.1 源码下载与编译
我推荐使用Nginx稳定版源码编译安装,这样可以灵活控制模块和优化参数。以下是自动下载和编译的脚本片段:
install_nginx() { NGINX_VERSION="1.20.1" NGINX_USER="www" NGINX_GROUP="www" # 创建运行用户 id -u $NGINX_USER &>/dev/null || useradd -M -s /sbin/nologin $NGINX_USER # 下载源码 wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz -P /usr/local/src/ tar zxf /usr/local/src/nginx-${NGINX_VERSION}.tar.gz -C /usr/local/src/ # 编译安装 cd /usr/local/src/nginx-${NGINX_VERSION} ./configure \ --user=$NGINX_USER \ --group=$NGINX_GROUP \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-pcre \ --with-stream make && make install }3.2 服务管理配置
为了方便管理,我们需要将Nginx设置为系统服务:
configure_service() { # 创建systemd服务文件 cat > /lib/systemd/system/nginx.service <<EOF [Unit] Description=nginx - high performance web server After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/bin/kill -s HUP \$MAINPID ExecStop=/bin/kill -s QUIT \$MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target EOF systemctl daemon-reload systemctl enable nginx }4. 安全加固与优化
4.1 基础安全配置
生产环境必须考虑安全因素,以下是几个关键配置项:
# 在nginx.conf的http块中添加 server_tokens off; # 隐藏Nginx版本信息 client_max_body_size 10m; # 限制上传文件大小 # 每个server块应该包含的基础安全头 add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block";4.2 性能优化参数
根据服务器配置调整以下参数可以显著提升性能:
worker_processes auto; # 自动设置为CPU核心数 worker_connections 10240; # 每个worker的最大连接数 # 启用高效文件传输模式 sendfile on; tcp_nopush on; tcp_nodelay on; # 连接超时设置 keepalive_timeout 65;5. 完整脚本与使用说明
5.1 一键部署完整脚本
将前面所有功能整合成一个完整的部署脚本:
#!/bin/bash # Nginx一键部署脚本 # 功能:自动安装依赖、编译安装Nginx、配置系统服务、基础安全加固 # 适用系统:CentOS 7/8, Ubuntu 18.04/20.04 set -e # 定义颜色输出 RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[0;33m' NC='\033[0m' # 检查系统 check_system() { if [ -f /etc/redhat-release ]; then OS="centos" OS_VERSION=$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release) elif [ -f /etc/lsb-release ]; then OS="ubuntu" OS_VERSION=$(grep DISTRIB_RELEASE /etc/lsb-release | cut -d= -f2) else echo -e "${RED}不支持的Linux发行版${NC}" exit 1 fi echo -e "${GREEN}检测到系统:${OS} ${OS_VERSION}${NC}" } # 安装依赖 install_dependencies() { echo -e "${YELLOW}正在安装依赖包...${NC}" if [ "$OS" = "centos" ]; then yum install -y gcc make pcre-devel zlib-devel openssl-devel wget else apt-get update apt-get install -y build-essential libpcre3 libpcre3-dev zlib1g-dev libssl-dev wget fi [ $? -ne 0 ] && echo -e "${RED}依赖安装失败${NC}" && exit 1 } # 安装Nginx install_nginx() { NGINX_VERSION="1.20.1" NGINX_USER="www" NGINX_GROUP="www" echo -e "${YELLOW}正在安装Nginx ${NGINX_VERSION}...${NC}" # 创建运行用户 if ! id -u $NGINX_USER &>/dev/null; then useradd -M -s /sbin/nologin $NGINX_USER echo -e "${GREEN}创建用户 ${NGINX_USER} 成功${NC}" fi # 下载源码 if [ ! -f "/usr/local/src/nginx-${NGINX_VERSION}.tar.gz" ]; then wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz -P /usr/local/src/ fi if [ ! -d "/usr/local/src/nginx-${NGINX_VERSION}" ]; then tar zxf /usr/local/src/nginx-${NGINX_VERSION}.tar.gz -C /usr/local/src/ fi # 编译安装 cd /usr/local/src/nginx-${NGINX_VERSION} ./configure \ --user=$NGINX_USER \ --group=$NGINX_GROUP \ --prefix=/usr/local/nginx \ --with-http_ssl_module \ --with-http_stub_status_module \ --with-http_gzip_static_module \ --with-pcre \ --with-stream make && make install [ $? -ne 0 ] && echo -e "${RED}Nginx编译安装失败${NC}" && exit 1 echo -e "${GREEN}Nginx安装完成${NC}" } # 配置系统服务 configure_service() { echo -e "${YELLOW}正在配置系统服务...${NC}" if [ ! -f "/lib/systemd/system/nginx.service" ]; then cat > /lib/systemd/system/nginx.service <<EOF [Unit] Description=nginx - high performance web server After=network.target remote-fs.target nss-lookup.target [Service] Type=forking PIDFile=/usr/local/nginx/logs/nginx.pid ExecStartPre=/usr/local/nginx/sbin/nginx -t ExecStart=/usr/local/nginx/sbin/nginx ExecReload=/bin/kill -s HUP \$MAINPID ExecStop=/bin/kill -s QUIT \$MAINPID PrivateTmp=true [Install] WantedBy=multi-user.target EOF fi systemctl daemon-reload systemctl enable nginx systemctl start nginx [ $? -ne 0 ] && echo -e "${RED}Nginx服务启动失败${NC}" && exit 1 echo -e "${GREEN}Nginx服务配置完成${NC}" } # 基础安全配置 security_config() { echo -e "${YELLOW}正在配置基础安全设置...${NC}" # 备份原始配置 cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf.bak # 修改配置 sed -i '/http {/a \ server_tokens off;\n client_max_body_size 10m;' /usr/local/nginx/conf/nginx.conf # 测试配置并重载 /usr/local/nginx/sbin/nginx -t && systemctl reload nginx [ $? -ne 0 ] && echo -e "${RED}安全配置应用失败${NC}" && exit 1 echo -e "${GREEN}基础安全配置完成${NC}" } # 主函数 main() { check_system install_dependencies install_nginx configure_service security_config echo -e "\n${GREEN}Nginx部署完成!${NC}" echo -e "Nginx版本:$(/usr/local/nginx/sbin/nginx -v 2>&1)" echo -e "服务状态:$(systemctl is-active nginx)" echo -e "访问地址:http://$(curl -s ifconfig.me)" } main5.2 使用说明与注意事项
执行权限:运行前需要给脚本添加执行权限
chmod +x install_nginx.sh执行方式:建议使用root用户执行
./install_nginx.sh常见问题处理:
- 如果编译失败,检查
/usr/local/src/nginx-版本号/objs/autoconf.err文件查看具体错误 - 端口冲突时修改
/usr/local/nginx/conf/nginx.conf中的监听端口 - 服务启动失败时查看
/usr/local/nginx/logs/error.log
- 如果编译失败,检查
后续管理:
# 启动服务 systemctl start nginx # 停止服务 systemctl stop nginx # 重载配置 systemctl reload nginx # 查看状态 systemctl status nginx
6. 脚本优化与扩展
6.1 参数化改造
让脚本更灵活,可以通过命令行参数指定版本、安装路径等:
while getopts "v:p:u:g:" opt; do case $opt in v) NGINX_VERSION=$OPTARG ;; p) INSTALL_PREFIX=$OPTARG ;; u) NGINX_USER=$OPTARG ;; g) NGINX_GROUP=$OPTARG ;; ?) echo "用法: $0 [-v 版本] [-p 安装路径] [-u 运行用户] [-g 运行用户组]" ;; esac done6.2 日志功能增强
添加详细的日志记录功能,便于排查问题:
LOG_FILE="/var/log/nginx_install.log" log() { echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a $LOG_FILE } # 使用示例 log "开始安装依赖包"6.3 多版本支持
扩展脚本以支持OpenResty、Tengine等Nginx变种:
install_openresty() { # OpenResty安装逻辑 ... } install_tengine() { # Tengine安装逻辑 ... } case $NGINX_TYPE in nginx) install_nginx ;; openresty) install_openresty ;; tengine) install_tengine ;; *) echo "不支持的Nginx类型" && exit 1 ;; esac7. 生产环境建议
在实际生产环境中部署时,还需要考虑以下方面:
配置分离:将不同站点的配置拆分为单独文件,放在
/usr/local/nginx/conf/conf.d/目录下日志轮转:配置logrotate实现日志自动切割
cat > /etc/logrotate.d/nginx <<EOF /usr/local/nginx/logs/*.log { daily missingok rotate 30 compress delaycompress notifempty create 640 www www sharedscripts postrotate [ -f /usr/local/nginx/logs/nginx.pid ] && kill -USR1 \$(cat /usr/local/nginx/logs/nginx.pid) endscript } EOF性能监控:启用stub_status模块并配置监控
location /nginx_status { stub_status on; access_log off; allow 127.0.0.1; deny all; }定期维护:设置计划任务检查Nginx状态并自动恢复
*/5 * * * * root /usr/bin/systemctl status nginx >/dev/null || systemctl restart nginx
通过这个完整的Shell脚本方案,我们实现了Nginx的一键化部署,涵盖了从环境准备、源码编译、服务配置到安全加固的全流程。这个脚本经过多次迭代优化,已经能够处理大多数常见部署场景。根据实际需求,你可以进一步扩展其功能,比如添加Let's Encrypt证书自动申请、负载均衡配置等功能模块。