What is the easiest way to run a single NodeJS scr

2019-08-18 09:06发布

问题:

Taken from Docker's documentation that if you want to run a standalone NodeJS script you are supposed to use the following command:

docker run -it --rm --name my-running-script -v "$PWD":/usr/src/app -w /usr/src/app node:8 node your-daemon-or-script.js

This works except that it's not possible to stop the script using Ctrl-C. How can I achieve that?

Here is my script.js:

console.log('Started - now try to kill me...');

setTimeout(function () {
   console.log('End of life.');
}, 10000);

回答1:

This note is hidden in the extended docker run documentation:

Note: A process running as PID 1 inside a container is treated specially by Linux: it ignores any signal with the default action. So, the process will not terminate on SIGINT or SIGTERM unless it is coded to do so.

The main Docker container process (your container's ENTRYPOINT or CMD or the equivalent specified on the command line) runs as process ID 1 inside the container. This is normally reserved for a special init process and is special in a couple of ways.

Possibly the simplest answer is to let Docker inject an init process for you as PID 1 by adding --init to your docker run command.

Alternatively, on Node you can register a signal event to explicitly handle SIGINT. For example, if I extend your script to have

process.on('SIGINT', function() {
    process.exit();
});

and then rebuild the image and re-run it, it responds to ^C.