Catch Sigterm NodeJS

When deploying a new version, I see the following in my console:
npm ERR! path /myapp
npm ERR! command failed
npm ERR! signal SIGTERM
npm ERR! command sh -c -- npx prisma migrate deploy && npm run start
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2023-06-30T16_08_55_359Z-debug-0.log
npm ERR! path /myapp
npm ERR! command failed
npm ERR! signal SIGTERM
npm ERR! command sh -c -- npx prisma migrate deploy && npm run start
npm ERR! A complete log of this run can be found in:
npm ERR! /root/.npm/_logs/2023-06-30T16_08_55_359Z-debug-0.log
I would like to catch this signal to make sure I gracefully shutdown the service. However, when I try to catch the SIGTERM it doesn't seem to get fired in my process (log line doesn't show up)?
process.on("SIGTERM", () => {
console.log("Shutting down!");
});
process.on("SIGTERM", () => {
console.log("Shutting down!");
});
Is there something else I am missing? Project id: 9e28999f-05b9-4b5c-9caf-7a1d7bd55312
7 Replies
Percy
Percy13mo ago
Project ID: 9e28999f-05b9-4b5c-9caf-7a1d7bd55312
Brody
Brody13mo ago
i have been able to capture sigterm in a go app, so maybe something in your codebase is registering a sigterm event handler and prematurely exiting and fwiw, you can only halt the kill for 3 seconds max
rgmvisser
rgmvisser13mo ago
Thanks for your response @Brody ! Maybe you're right, but when I just locally run this:
setTimeout(() => {
console.log("SIGTERM timeout");
process.kill(process.pid, "SIGTERM");
}, 5000);
setTimeout(() => {
console.log("SIGTERM timeout");
process.kill(process.pid, "SIGTERM");
}, 5000);
The logs are showing up just fine 🤔
Brody
Brody13mo ago
after doing some quick Google searches, looks like this behaviour is a known problem and wouldn't be isolated to just railway, but docker in general
Ray
Ray13mo ago
command sh -c -- npx
spawns a shell that runs your actual command, so any signal traps gets to that shell first and doesn't propagate to your process there might be ways around this, perhaps google for "npx/npm shell interrupt signal" or do a custom build with a custom init?
rgmvisser
rgmvisser13mo ago
Thanks for your replies! I can't really find something that will do this, it looks like npm it self is spawnning command sh -c -- npx so I can't really customize anything there. @Brody where did you find this was a general docker problem? I wasn't able to come across that, but would love to read and see if they have some workarounds
Brody
Brody13mo ago
I just googled for "nodejs not catching sigterm in docker" and one of the recommendations was doing a custom init like ray suggested