手动编译安装 Nginx 并配置开机自启(Root用户)

手动编译安装 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. 常用命令

功能命令
启动 Nginxsystemctl start nginx
停止 Nginxsystemctl stop nginx
重启 Nginxsystemctl 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

🎯 总结

通过本教程,你已经完成:

  1. 手动编译安装 Nginx(非 apt/yum 安装)。
  2. 配置 Systemd 服务,实现开机自启。
  3. 验证 Nginx 自动启动,确保服务器重启后服务可用。

适用于 生产环境部署,确保 Nginx 稳定运行。 🚀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值