How to send HUP signal and zero downtime restart nginx server using Node.js file
You need three things:
The PID of your nginx server. Stored in:
A command to send a
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.
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 it reload-nginx
- Put the following with the following lines inside reload-nginx.
%devis 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.