在 EulerOS 2.0 (64位) 上配置 Nginx 开机自启,核心逻辑其实和 CentOS/RHEL 系列是一致的,因为 EulerOS 底层兼容 RPM 包管理体系。
这里分两种情况:如果你是用 yum/dnf 安装的(推荐)和 如果你是编译安装或者解压二进制包安装的。大多数生产环境为了维护方便,建议走 yum 源安装或官方提供的 rpm 包。
方法一:通过 systemd 管理(最标准、推荐)
EulerOS 2.0 默认使用 systemd 作为初始化系统。只要 Nginx 的启动脚本位于 /usr/lib/systemd/system/ 或 /etc/systemd/system/ 目录下,且文件名为 nginx.service,那么它通常已经具备开机自启能力,或者只需简单几步即可开启。
1. 检查服务状态
首先确认 Nginx 是否已经安装了 systemd 单元文件:
systemctl status nginx
如果显示 Unit nginx.service could not be found.,说明没有服务文件,请跳到方法二。
如果显示了服务信息,但状态是 inactive (dead) 或 enabled/disabled 不确定,继续下一步。
2. 启用开机自启
执行以下命令将 Nginx 加入开机启动列表:
systemctl enable nginx
输出类似 Created symlink /etc/systemd/system/multi-user.target.wants/nginx.service → /usr/lib/systemd/system/nginx.service. 即表示成功。
3. 立即启动并验证
# 启动服务
systemctl start nginx
# 查看运行状态
systemctl status nginx
# 重启服务器测试(可选,正式环境慎用)
reboot
重启后再次登录,执行 systemctl is-enabled nginx,如果返回 enabled,则配置成功。
方法二:手动创建 systemd 服务文件(适用于编译安装/二进制包)
如果你是从源码编译安装 Nginx,或者下载的是二进制压缩包,系统不会自动识别 Nginx 为服务。你需要手动创建一个 .service 文件。
假设你的 Nginx 安装在 /usr/local/nginx,可执行文件在 /usr/local/nginx/sbin/nginx。
1. 创建服务文件
使用 root 权限编辑文件:
vi /etc/systemd/system/nginx.service
写入以下内容(根据实际路径修改 ExecStart 和 ExecReload):
[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/run/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
注意:
ExecStartPre用于启动前检查配置文件语法是否正确,避免错误配置导致无法启动。PIDFile路径需确保 Nginx 配置文件中pid指令指向的位置一致,或者让 Nginx 自己生成。如果没指定 pid 文件,可以删除PIDFile行,并将Type改为simple。
2. 重载 systemd 守护进程
修改服务文件后,必须通知 systemd 重新加载配置:
systemctl daemon-reload
3. 启用并启动
systemctl enable nginx
systemctl start nginx
systemctl status nginx
常见问题排查
-
端口被占用
启动失败时,先检查 80/443 端口是否被其他程序占用:netstat -tlnp | grep :80 # 或 ss -tlnp | grep :80 -
SELinux 限制
EulerOS 可能默认开启 SELinux。如果 Nginx 能启动但网页打不开,可能是 SELinux 阻止了访问。- 临时关闭测试:
setenforce 0 - 永久解决:保持 SELinux 开启,设置正确上下文:
restorecon -Rv /usr/local/nginx/html # 或者允许 httpd 连接网络(如果是反向XX场景) setsebool -P httpd_can_network_connect 1
- 临时关闭测试:
-
防火墙问题
确保防火墙放行了 80 和 443 端口:firewall-cmd --permanent --add-service=http firewall-cmd --permanent --add-service=https firewall-cmd --reload
总结
对于 EulerOS 2.0,优先使用 systemctl enable nginx。这是最干净、最符合 Linux 规范的做法。只有在你完全控制 Nginx 安装路径且无现成服务文件时,才需要手动编写 .service 文件。
不要再用 chkconfig 或修改 /etc/rc.local 了,那些是旧时代的做法,在 systemd 环境下不仅不保证生效,还可能带来冲突。
云技术博客