How to send HUP signal and zero downtime restart nginx server using Node.js file
2 Answers
You need three things:
The PID of your nginx server. Stored in:
/var/run/nginx.pid
A command to send a
SIGHUP
(1
) to the process with that PID:kill -1 $(cat /var/run/nginx.pid)
A way for node.js to send the
kill
. I'd go with a child process.
I'm not a Node developer. I have no way to put these together into something that makes sense, but that's what you'd do if you knew what you were doing.
Oh and your nginx server and Node.JS app need to be running as the same user to allow Node to send the signal. This is fairly easily done but may have security ramifications. You may instead want to make a SUID script for Node to call but if done carelessly, these can also have security ramifications.
Alternatively, you could use the process
module to run process.kill(...)
. You'll still need to read in the PID for nginx and the permissions still need to be sorted.
Something like this (again, I'm still not a Node dev, so this might be syntactically incorrect):
var fs = require('fs'),
process = require('process');
process.kill(fs.readFileSync('/var/run/nginx.pid', "utf8"), 'SIGHUP');
create a file inside
/etc/sudoers.d/
. Call itreload-nginx
Put the following with the following lines inside
reload-nginx
.%dev
is user group of multiple users who can want to reload nginx. You can also restrict this privilege to a single user%dev ALL=(ALL) NOPASSWD: /bin/systemctl reload nginx.service %dev ALL=(ALL) NOPASSWD: /bin/systemctl reload nginx
Once this is done, anyone belonging to the %dev
group will be able to reload nginx without entering their password. You can immediately test this from the command line.
Add entries for the user under which nodejs will run and then use nodejs' child_process
module to invoke unix shell commands like sudo systemctl reload nginx
. This should do the trick.

- 70,465

- 101
- 3