手动编译安装 Nginx 并配置开机自启(Root用户)
本教程详细讲解如何在 Linux 服务器上 手动编译安装 Nginx,并配置 Systemd 服务 实现开机自启。
适用于 Ubuntu/CentOS/Debian 等主流 Linux 发行版(无需 apt/yum
,直接源码编译安装)。
📌 1. 安装依赖环境
在编译 Nginx 前,先安装必要的依赖库:
# Ubuntu/Debian
apt update && apt install -y build-essential libpcre3 libpcre3-dev zlib1g zlib1g-dev openssl libssl-dev
# CentOS/RHEL
yum install -y gcc make pcre pcre-devel zlib zlib-devel openssl openssl-devel
📌 2. 下载并编译 Nginx
(1) 下载 Nginx 源码
cd /usr/local/src
wget https://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
(2) 编译安装
./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_v2_module
make && make install
--prefix=/usr/local/nginx
:指定安装目录(默认在/usr/local/nginx
)。--with-http_ssl_module
:启用 HTTPS 支持(如需 SSL 证书)。
📌 3. 启动 Nginx
(1) 直接启动测试
/usr/local/nginx/sbin/nginx
-
检查是否运行:
ps -ef | grep nginx
应显示
master
和
worker
进程。
(2) 访问测试
curl -I http://localhost
如果返回 HTTP/1.1 200 OK
,说明 Nginx 正常运行。
📌 4. 配置 Systemd 开机自启
(1) 创建 Systemd 服务文件
vim /etc/systemd/system/nginx.service
粘贴以下内容(适配你的安装路径):
[Unit]
Description=Nginx HTTP Server
After=network.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s quit
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
(2) 重新加载 Systemd 并启用自启
systemctl daemon-reload
systemctl enable nginx
systemctl start nginx
(3) 检查服务状态
systemctl status nginx
-
正常应显示
active (running)
。 -
如果失败,查看日志:
journalctl -u nginx -xe
📌 5. 验证开机自启
reboot
重启后检查 Nginx 是否自动运行:
ps -ef | grep nginx
systemctl status nginx
📌 6. 常用命令
功能 | 命令 |
---|---|
启动 Nginx | systemctl start nginx |
停止 Nginx | systemctl stop nginx |
重启 Nginx | systemctl restart nginx |
重载配置 | systemctl reload nginx |
查看状态 | systemctl status nginx |
测试配置 | /usr/local/nginx/sbin/nginx -t |
📌 7. 可能遇到的问题
问题 1:systemctl status nginx
显示 inactive (dead)
-
原因:Nginx 未以 Systemd 方式启动(可能是手动
/usr/local/nginx/sbin/nginx
启动的)。
解决
:
killall nginx
systemctl start nginx
问题 2:nginx.pid
文件不存在
-
原因:Nginx 未正确生成 PID 文件。
解决
:在
nginx.conf
中指定 PID 路径:
pid /usr/local/nginx/logs/nginx.pid;
然后重启 Nginx:
systemctl restart nginx
🎯 总结
通过本教程,你已经完成:
- 手动编译安装 Nginx(非
apt/yum
安装)。 - 配置 Systemd 服务,实现开机自启。
- 验证 Nginx 自动启动,确保服务器重启后服务可用。
适用于 生产环境部署,确保 Nginx 稳定运行。 🚀