本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
要实现 Nginx 在系统启动时自动运行,可以通过以下几种方式进行设置,本文将针对不同的操作系统 (包括 Linux, Windows 和 macOS) 分别介绍。
Linux 操作系统:
- 使用 Systemd 服务
对于使用 Systemd 管理服务的 Linux 发行版,例如 Ubuntu 16.04 及以后的版本、CentOS 7 及以后的版本等,我们可以通过以下方法将 Nginx 设置为开机自启动:
首先,在创建 Nginx 服务文件之前,我们需要确保 Nginx 已经成功安装在系统上。然后,创建一个名为 nginx.service的服务文件:
[Unit]
Description=The Nginx HTTP and reverse proxy server
After=network.target
[Service]
Type=forking
PIDFile=/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target
复制并粘贴以下内容到该文件:
$ sudo systemctl enable nginx
$ sudo systemctl start nginx
保存并关闭文件。然后,运行以下命令启动 Nginx 服务并设置开机自启:
@echo off
start /b /d "C:\path\to\nginx" nginx.exe
- 使用 SysV Init
对于早期使用 SysV Init 管理服务的 Linux 发行版,例如 Ubuntu 14.04、CentOS 6 等,可以通过以下方式将 Nginx 设置为开机自启:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>homebrew.mxcl.nginx</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/opt/nginx/bin/nginx</string>
<string>-g</string>
<string>daemon off;</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/usr/local/var/log/nginx/error.log</string>
<key>StandardOutPath</key>
<string>/usr/local/var/log/nginx/access.log</string>
</dict>
</plist>
Windows 操作系统:
若想要设置 Nginx 在 Windows 开机启动,可以通过以下方法实现:
- 新建一个名称为 “nginx-start.bat” 的批处理脚本,并填写以下内容:
@echo off
start /b /d "C:\path\to\nginx" nginx.exe
请注意将 C:\path\to\nginx替换成实际 Nginx 安装路径。
- 在 Windows 文件资源管理器中,通过以下路径进入系统的启动文件夹:
%APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup
将之前创建好的 “nginx-start.bat” 文件复制到此文件夹。
此时,Nginx 应已设置为 Windows 开机自启动。
macOS 操作系统:
对于 macOS 用户,可以使用以下方法将 Nginx 设置为开机自启:
- 创建一个名为
homebrew.mxcl.nginx.plist的文件,并将其保存在~/Library/LaunchAgents路径下。编辑文件并写入以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>homebrew.mxcl.nginx</string>
<key>ProgramArguments</key>
<array>
<string>/usr/local/opt/nginx/bin/nginx</string>
<string>-g</string>
<string>daemon off;</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/usr/local/var/log/nginx/error.log</string>
<key>StandardOutPath</key>
<string>/usr/local/var/log/nginx/access.log</string>
</dict>
</plist>
- 接着,运行以下命令将创建的 plist 文件加载到 launchd 服务并启动 Nginx:
$ launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.nginx.plist
以上便是不同操作系统下设置 Nginx 开机自启动的方法。通过这些设置,您的 Nginx 服务器可以在系统启动时自动运行,从而提高您管理服务器的效率。