Node.js Docker Service Tips
Jacob Korsgaard
Posted on March 16, 2021
Last time I deployed some docker containers remotely to Unraid. Now let me share a tip or two for the node.js part of those containers.
Graceful exit
Node.js applications do not automatically know how to gracefully shut down when a container is stopped. To do this you'll have to handle signals.
I followed this nice guide: Building Graceful Node Applications in Docker and they got the signal handling from here Trapping signals in Docker containers.
The crux of the code is to add a listener to process
:
function shutdown() {
// close your server here
process.exit();
}
process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);
Node.JS Signal Events Documentation doesn't call process.exit()
but it turns out Docker does funny things due to the process having ID 1, this is the most up to date post I've found about that issue: Top 4 Tactics To Keep Node.js Rockin’ in Docker see "Start Node Directly in Dockerfiles".
Container content not updating
Another issue I ran into with my node.js container was that when I made changes to my index.js
and ran the command to deploy my containers to Unraid, the Unraid nodeserver container would not have my changes.
I searched for a solution and -no-cache
and --force-recreate
were both suggested, but these methods did not fix the problem.
The only thing I found that actually fixed the issue was to remove the container and images from Unraid before building new ones and deploying those.
docker-compose --context unraid -f docker-compose.yml -f docker-compose.prod.yml down --rmi local
docker-compose --context unraid -f docker-compose.yml -f docker-compose.prod.yml up --build -d
Now, arguably an even better way would be to not put the index.js into the container, but instead mount a path to run index.js from. Then just restart the nodeserver container when I made changes. Which is probably what I would do in the future for iteration.
Posted on March 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.