1. 下载 WinSW
访问官方 GitHub 发布页:
https://github.com/winsw/winsw/releases
下载最新稳定版(如 WinSW-x64.exe),建议重命名为 nginx-service.exe,便于识别。
# 示例:将下载的文件重命名
mv WinSW-x64.exe nginx-service.exe
WinSW 是单文件可执行程序,无需安装,直接使用。
2. 创建配置文件 nginx-service.xml
在同一目录下创建 nginx-service.xml,内容如下:
html
<service>
<id>nginx</id>
<name>Nginx Web Server</name>
<description>High-performance web server with reverse proxy capabilities</description>
<executable>C:\nginx\nginx.exe</executable>
<workingdirectory>C:\nginx</workingdirectory>
<logmode>rotate</logmode>
<onfailure action="restart" delay="10 sec"/>
<resetfailure>1 hour</resetfailure>
<startmode>Automatic</startmode>
<stopmode>Automatic</stopmode>
<logpath>C:\nginx\logs</logpath>
<logmode>roll</logmode>
<depend>Tcpip</depend>
</service>
关键配置说明:
<id>:服务唯一标识符(必须唯一)
<executable>:Nginx 主程序路径(请确保路径正确)
<workingdirectory>:工作目录,确保 Nginx 能正确加载配置
<startmode>Automatic</startmode>:实现开机自启的核心配置
<logpath>:指定日志输出目录,便于排查问题
3. 安装服务
以管理员身份打开命令提示符(CMD)或 PowerShell,执行:
javascript
cd C:\nginx
nginx-service.exe install
成功后会输出:Service installed successfully.
4. 启动服务并验证
yaml
net start nginx
sc query nginx
检查状态是否为 RUNNING,并打开 services.msc,确认:
yaml
服务名称:Nginx Web Server
启动类型:自动
状态:已启动
访问 http://localhost,确认页面正常加载。
5. 卸载服务
yaml
nginx-service.exe uninstall
日志与故障排查
WinSW 会自动生成日志文件在 C:\nginx\logs\ 目录下,文件名为:
nginx-service.out.log:标准输出
nginx-service.err.log:错误输出
若服务无法启动,请检查:
Nginx 配置是否正确:
yaml
C:\nginx\nginx.exe -t
路径是否包含空格或中文?建议使用 C:\nginx 这类简洁路径。
是否以管理员身份运行 install 命令?