windows 下将 nginx 安装为服务

2021-12-14  本文已影响0人  纯爱枫若情

在 linux 和 mac 下面,可以很快捷的通过各种工作或者源码编译的方式,安装使用 nginx。

但是由于平台的原因,在 windows 下大部分人都是直接用的 nginx 官方提供的二进制包。这个二进制包,下载下来以后,双击就能直接运行 nginx,在免安装模式下就能用。

Pasted image 20211215104756.png

但是问题是,虽然 nginx 很稳定,一般不会轻易挂掉,但是 windows 系统不像 linux 机器一样,一旦开机,如果不是由于断电或者服务器故障这种意外的情况发生,一般都不会关机。正常情况下,大部分人在用完 nginx 机器以后,都会顺手关机掉,这样下次再想用,又得手动启动对应的二进制文件,过于麻烦。

有没有一种比较好的方案呢?

答案当然是肯定的,为了让 nginx 在 windows 上能自动运行,需要将其注册成 windows 系统的服务。

在 windows 系统里,大致有几种不同的方式:

1. 直接用 powershell 的命令

在微软的官网,提供了一种方式,可以将可执行文件,安装为 windows services 服务:如何:安装和卸载 Windows 服务

Pasted image 20211215110035.png

但是我经过尝试以后,最终以失败告终。确实可以安装成功,但是 nginx 没法成功启动,个人猜想,应该是没有将对应的启动参数写入注册表,导致会失败。

虽然尝试失败了,但是从这里,其实我们也能得到一点经验教训。

我们能看出来,其实 windows 上 PowerShell 功能还挺强大的,可以干很多事情,如果有兴趣的话,倒是可以深入研究一下。

2. 采用 winsw 软件

winsw 是一款辅助将程序注册成 windows 服务的工具,https://github.com/kohsuke/winsw

下载下来以后,需要进行一番配置,至于如何使用,我这里就不详细的提及了,如果感兴趣的人,可以去 StackOverflow 上,看相关讨论:
https://stackoverflow.com/questions/10061191/add-nginx-exe-as-windows-system-service-like-apache

但是这个方案,在我的 win11 上最终也以失败告终,注册成服务后,可以启动,但是想要通过服务来停止运行 nginx,就会出现以下错误:

2021-12-15T09:46:36.393 DEBUG service - Stopping process 'nginx (9128)'...

2021-12-15T09:46:36.410 ERROR service - Failed to stop service.

System.InvalidOperationException: Process was not started by this object, so requested information cannot be determined.

 at System.Diagnostics.Process.EnsureState(State ) in System.Diagnostics.Process.dll:token 0x60000e4+0xe1

 at System.Diagnostics.Process.get_ExitCode() in System.Diagnostics.Process.dll:token 0x60000d1+0x0

 at WinSW.Util.ProcessExtensions.StopPrivate(Process process, Int32 millisecondsTimeout) in WinSW.Core.dll:token 0x60000ca+0x5a

 at WinSW.Util.ProcessExtensions.StopTree(Process process, Int32 millisecondsTimeout) in WinSW.Core.dll:token 0x60000c6+0x0

 at WinSW.Util.ProcessExtensions.StopTree(Process process, Int32 millisecondsTimeout) in WinSW.Core.dll:token 0x60000c6+0x2b

 at WinSW.WrapperService.DoStop() in WinSW.Core.dll:token 0x60000bb+0x267

 at WinSW.WrapperService.OnStop() in WinSW.Core.dll:token 0x60000b7+0x0

所以,因为存在没法正常退出的问题,会导致,如果重启电脑以后,没法正常的自启动该服务。

如果有童鞋碰到的一样的问题,感兴趣的话,可以深究一下原因。

3. 采用 nssm 软件

最后找到了这款软件,用了一下,最终一下子就解决了将 nginx 注册成服务的问题。

主要有这么几步操作:

如果不知道如何操作的,可以详细的参考下 StackOverflow 上的这个回答:

Pasted image 20211215112124.png

最后送上该问题链接:https://stackoverflow.com/questions/40846356/run-nginx-as-windows-service

4. 采用 chocolately 安装 nginx

其实,windows 上也有比较好用的包管理工具 —— chocolately,如果我们安装 nginx 的时候,是直接采用 chocolately 的方式,那么 nginx 就会被自己注册成服务了。

Pasted image 20211215113448.png

如果有安装过 chocolately 的童鞋,直接运行命令 choco install nginx,就能直接安装 nginx 了。

上一篇 下一篇

猜你喜欢

热点阅读