How to fix docker NodeJS container not shutting down
When you are running a NodeJS server inside a docker container, you will often encouter the issue that the container does not shutdown properly but taking a long time (several minutes) to shutdown.
In order to fix this, add the following code to your main NodeJS file (typically you should add it at the top of the file to make sure nothing prevents it from getting executed)
process.on('SIGTERM', function() {
console.log('SIGTERM received, shutting down...');
process.exit(0);
});
process.on('SIGINT', function() {
console.log('SIGINT received, shutting down...');
process.exit(0);
});
This will force NodeJS to exit (more or less immediately) once either SIGINT
or SIGTERM
is received. Typically, Docker sendsĀ SIGTERM
on container shutdown.
Background information
See this GitHub guide