Nginx服务配置为Windows系统服务

Nginx服务配置为Windows系统服务+日志处理

参考引用:

http://www.yaohaixiao.com/blog/how-to-configure-nginx-service-as-windows-system-service/
https://www.xilixili.net/2018/01/04/winsw-with-nginx/
https://github.com/winsw/winsw

winsw+nginx安装步骤

  1. 下载winsw.exe文件,重命名为nginx-service.exe
  2. 创建nginx-service.xml文件。
  3. 将nginx-service.exe和nginx-service.xml放在nginx.exe的同一目录下。
  4. 运行nginx-service.exe install nginx-service.xml安装服务;winsw install
  5. 运行nginx-service.exe start nginx-service.xml运行服务;winsw install
  6. 运行nginx-service.exe status nginx-service.xml查看服务状态;winsw status

CLI命令文档:https://github.com/winsw/winsw/blob/v3/docs/cli-commands.md#cli-commands
配置文件说明文档:https://github.com/winsw/winsw/blob/v3/docs/xml-config-file.md
配置文件示例:https://github.com/winsw/winsw/blob/v3/samples

运行目录:

1
2
3
4
5
6
7
E:nginx
│ nginx.exe
├─nginx-winsw
│ │ nginx-service.exe
│ │ nginx-service.xml
│ └─wswlogs
│ nginx-service.wrapper.log
  • 包装器及其子进程的默认工作目录是配置文件所在的目录。设置workingdirectory可以更改工作目录。
    • 未设置workingdirectory值的情况下,设置executable为E:\nginx\nginx.exe,默认执行路径为E:\nginx\nginx-winsw\nginx.exe
    • 设置workingdirectory值为E:\nginx,设置executable为E:\nginx\nginx.exe,执行路径为:E:\nginx\nginx.exe
  • 配置文件中,<logpath>日志文件夹的路径是相对于nginx-service.exe所在目录,它的根目录是nginx-service.exe所在目录。受限于nginx-service.exe所在目录。不受workingdirectory值影响。
  • 在未设置workingdirectory情况下,默认工作目录为nginx-service.exe所在目录,所以nginx-service.exe必须和nginx.exe在同一目录下才能成功启动。

sample.xml:

sample.xml
1
2
3
4
5
6
7
8
9
10
<service>
<id>jenkins</id>
<name>Jenkins</name>
<description>This service runs Jenkins continuous integration system.</description>
<env name="JENKINS_HOME" value="%BASE%"/>
<executable>java</executable>
<arguments>-Xrs -Xmx256m -jar "%BASE%\jenkins.war" --httpPort=8080</arguments>
<log mode="roll"></log>
</service>

nginx-service.xml:

nginx-service.xml
1
2
3
4
5
6
7
8
9
10
11
<service>
<id>nginx</id>
<name>nginx</name>
<description>nginx服务</description>
<logpath>./logs</logpath>
<logmode>roll</logmode>
<executable>nginx.exe</executable>
<stopexecutable>nginx.exe</stopexecutable>
<stopargument>-s</stopargument>
<stopargument>stop</stopargument>
</service>
自定义workingdirectory.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
<!--
MIT License

Copyright (c) 2008-2020 Kohsuke Kawaguchi, Sun Microsystems, Inc., CloudBees,
Inc., Oleg Nenashev and other contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
-->

<!--
This is a sample configuration of the Windows Service Wrapper.
This configuration file should be placed near the WinSW executable, the name should be the same.
E.g. for myapp.exe the configuration file name should be myapp.xml

You can find more information about configuration options here: https://github.com/kohsuke/winsw/blob/master/doc/xmlConfigFile.md
-->
<service>

<!--
SECTION: Mandatory options
All options in other sections are optional
-->

<!-- ID of the service. It should be unique accross the Windows system-->
<id>nginxservice</id>
<!-- Display name of the service -->
<name>Nginx Service (powered by WinSW)</name>
<!-- Service description -->
<description>Nginx包装成Windows服务</description>

<!-- Path to the executable, which should be started -->
<executable>E:\nginx\nginx.exe</executable>

<!--
SECTION: Installation
These options are being used during the installation only.
Their modification will not take affect without the service re-installation.
-->

<!--
OPTION: serviceaccount
Defines account, under which the service should run.
-->
<!--
<serviceaccount>
<domain>YOURDOMAIN</domain>
<user>useraccount</user>
<password>Pa55w0rd</password>
<allowservicelogon>true</allowservicelogon>
</serviceaccount>
-->

<!--
OPTION: onfailure
Defines a sequence of actions, which should be performed if the managed executable fails.
Supported actions: restart, reboot, none
-->
<!--
<onfailure action="restart" delay="10 sec"/>
<onfailure action="restart" delay="20 sec"/>
<onfailure action="reboot" />
-->

<!--
OPTION: resetfailure
Time, after which the Windows service resets the failure status.
Default value: 1 day
-->
<!--
<resetfailure>1 hour</resetfailure>
-->

<!--
OPTION: securityDescriptor
The security descriptor string for the service in SDDL form.
For more information, see https://docs.microsoft.com/windows/win32/secauthz/security-descriptor-definition-language.
-->

<!--<securityDescriptor></securityDescriptor>-->

<!--
SECTION: Executable management
-->

<!--
OPTION: arguments
Arguments, which should be passed to the executable
-->
<!--
<arguments>-classpath c:\cygwin\home\kohsuke\ws\hello-world\out\production\hello-world test.Main</arguments>
-->

<!--
OPTION: startarguments
Arguments, which should be passed to the executable when it starts
If specified, overrides 'arguments'.
-->
<!--
<startarguments></startarguments>
-->

<!--
OPTION: workingdirectory
If specified, sets the default working directory of the executable
Default value: Directory of the service wrapper executable.
-->

<workingdirectory>E:\nginx</workingdirectory>


<!--
OPTION: priority
Desired process priority.
Possible values: Normal, Idle, High, RealTime, BelowNormal, AboveNormal
Default value: Normal
-->
<priority>Normal</priority>

<!--
OPTION: stoptimeout
Time to wait for the service to gracefully shutdown the executable before we forcibly kill it
Default value: 15 seconds
-->
<stoptimeout>15 sec</stoptimeout>

<!--
OPTION: stopparentprocessfirst
If set, WinSW will terminate the parent process before stopping the children.
Default value: true
-->
<stopparentprocessfirst>true</stopparentprocessfirst>


<!--
OPTION: stopexecutable
Path to an optional executable, which performs shutdown of the service.
This executable will be used if and only if 'stoparguments' are specified.
If 'stoparguments' are defined without this option, 'executable' will be used as a stop executable
-->

<stopexecutable>E:\nginx\nginx.exe</stopexecutable>


<!--
OPTION: stoparguments
Additional arguments, which should be passed to the stop executable during termination.
This OPTION also enables termination of the executable via stop executable
-->
<!-- 快速退出 -->
<stoparguments>-s stop</stoparguments>
<!-- 退出 -->
<!-- <stoparguments>-s quit</stoparguments> -->


<!--
SECTION: Service management
-->
<!--
OPTION: startmode
Defines start mode of the service.
Supported modes: Automatic, Manual, Boot, System (latter ones are supported for driver services only)
Default mode: Automatic
-->
<startmode>Automatic</startmode>

<!--
OPTION: delayedAutoStart
Enables the Delayed Automatic Start if 'Automatic' is specified in the 'startmode' field.
See the WinSW documentation to get info about supported platform versions and limitations.
-->
<!--<delayedAutoStart/>-->

<!--
OPTION: depend
Optionally specifies services that must start before this service starts.
-->
<!--
<depend>Eventlog</depend>
<depend>W32Time</depend>
-->

<!--
OPTION: waithint
The estimated time required for a pending stop operation.
Before the specified amount of time has elapsed, the service should make its next call to the SetServiceStatus function.
Otherwise the service will be marked as non-responding
Default value: 15 seconds
-->
<waithint>15 sec</waithint>

<!--
OPTION: sleeptime
The time before the service should make its next call to the SetServiceStatus function.
Do not wait longer than the wait hint. A good interval is one-tenth of the wait hint but not less than 1 second and not more than 10 seconds.
Default value: 1 second
-->
<sleeptime>1 sec</sleeptime>

<!--
OPTION: interactive
Indicates the service can interactwith the desktop.
-->
<!--
<interactive/>
-->

<!--
SECTION:Logging
-->

<!--
OPTION: logpath
Sets a custom logging directory for all logs being produced by the service wrapper
Default value: Directory, which contains the executor
-->

<logpath>./wswlogs</logpath>


<!--
OPTION: log
Defines logging mode for logs produced by the executable.
Supported modes:
* append - Rust update the existing log
* none - Do not save executable logs to the disk
* reset - Wipe the log files on startup
* roll - Roll logs based on size
* roll-by-time - Roll logs based on time
* rotate - Rotate logs based on size, (8 logs, 10MB each). This mode is deprecated, use "roll"
Default mode: append

Each mode has different settings.
See https://github.com/kohsuke/winsw/blob/master/doc/loggingAndErrorReporting.md for more details
-->
<log mode="roll-by-time">
<pattern>yyyyMMdd</pattern>
</log>

<!--
SECTION: Environment setup
-->
<!--
OPTION: env
Sets or overrides environment variables.
There may be multiple entries configured on the top level.
-->
<!--
<env name="MY_TOOL_HOME" value="C:\etc\tools\myTool" />
<env name="LM_LICENSE_FILE" value="host1;host2" />
-->


<!--
OPTION: download
List of downloads to be performed by the wrapper before starting
-->
<!--
<download from="http://www.google.com/" to="%BASE%\index.html" />

Download and fail the service startup on Error:
<download from="http://www.nosuchhostexists.com/" to="%BASE%\dummy.html" failOnError="true"/>

An example for unsecure Basic authentication because the connection is not encrypted:
<download from="http://example.com/some.dat" to="%BASE%\some.dat"
auth="basic" unsecureAuth=“true”
username="aUser" password=“aPassw0rd" />

Secure Basic authentication via HTTPS:
<download from="https://example.com/some.dat" to="%BASE%\some.dat"
auth="basic" username="aUser" password="aPassw0rd" />

Secure authentication when the target server and the client are members of the same domain or
the server domain and the client domain belong to the same forest with a trust:
<download from="https://example.com/some.dat" to="%BASE%\some.dat" auth="sspi" />
-->

<!--
SECTION: Other options
-->

<!--
OPTION: beeponshutdown
Indicates the service should beep when finished on shutdown (if it's supported by OS).
-->
<!--
<beeponshutdown/>
-->

<!--
SECTION: Extensions
This configuration section allows specifying custom extensions.
More info is available here: https://github.com/kohsuke/winsw/blob/master/doc/extensions/extensions.md
-->

<!--
<extensions>
Extension 1: id values must be unique
<extension enabled="true" id="extension1" className="winsw.Plugins.SharedDirectoryMapper.SharedDirectoryMapper">
<mapping>
<map enabled="false" label="N:" uncpath="\\UNC"/>
<map enabled="false" label="M:" uncpath="\\UNC2"/>
</mapping>
</extension>
...
</extensions>
-->

</service>

nginx-service.exe 和nginx-service.xml文件路径:

tree.bat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
D:nginx
nginx-service.exe
nginx-service.xml
nginx.exe

├─conf

├─contrib

├─docs

├─html

├─logs

└─temp

widows 命令:

echo.bat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@ECHO OFF
REM 声明采用UTF-8编码
chcp 65001
@REM 启动
echo 启动 nginx-service.exe start

@REM 停止
echo 停止 nginx-service.exe stop

@REM 安装
echo 安装 nginx-service.exe install

@REM 卸载
echo 卸载 nginx-service.exe uninstall

pause

Nginx日志处理

思路

nginx -s reopen命令控制Nginx重新打开日志文件(生成文件)的,通过WinSW封装一个reopen的操作的服务(可以保证SYSTEM权限),剩下的就是定时任务了(注意运行账户改为SYSTEM)。

Nginx Logrote Service 批处理文件样例

logservice.xml
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8" ?>
<service>
<id>nginx-logrote</id>
<name>Nginx Logrote Service</name>
<description>基于Nginx的媒体流服务器的Logrote服务</description>
<executable>cleanlog.bat</executable>
<startmode>Manual</startmode>
<logpath>./logs</logpath>
<logmode>roll</logmode>
</service>
cleanlog.bat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ECHO OFF
CD logs

FOR /f "delims=" %%i IN ('DIR /a-d /b access.log') DO (
IF %%~zi gtr 10485760 (
MOVE /Y %%i %%i.bak
)
)

FOR /f "delims=" %%i IN ('DIR /a-d /b error.log') DO (
IF %%~zi gtr 10485760 (
MOVE /Y %%i %%i.bak
)
)

CD ..
nginx -s reopen

快捷bat

卸载重装wsw
1
2
3
nginx-service.exe uninstall nginx-service.xml
nginx-service install nginx-service.xml
pause
开启wsw服务
1
2
nginx-service start nginx-service.xml
nginx-service status nginx-service.xml
停止wsw服务
1
nginx-service stop nginx-service.xml
作者

zhang

发布于

2022-04-21

更新于

2023-09-19

许可协议

CC BY-NC-SA 4.0

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×