取自 Docker 的文档,如果你想运行独立的 NodeJS 脚本,你应该使用以下命令:
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
除了无法使用 Ctrl-C 停止脚本之外,此方法有效。我怎样才能实现这一目标?
这是我的 script.js:
console.log('Started - now try to kill me...');
setTimeout(function () {
console.log('End of life.');
}, 10000);
最佳答案
此注释隐藏在 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
orSIGTERM
unless it is coded to do so.
主 Docker 容器进程(容器的 ENTRYPOINT
或 CMD
或命令行上指定的等效进程)在容器内作为进程 ID 1 运行。这通常是为特殊的 init 进程保留的,并且在几个方面很特殊。
可能最简单的答案是通过将 --init
添加到 docker run
命令中,让 Docker 为您注入(inject)一个 init 进程作为 PID 1。
或者,您可以在 Node 上注册 signal event显式处理 SIGINT
。例如,如果我将您的脚本扩展为
process.on('SIGINT', function() {
process.exit();
});
然后重建镜像并重新运行它,它会响应 ^C。
关于node.js - 使用 Docker 运行单个 NodeJS 脚本并能够使用 Ctrl-C 终止它的最简单方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56288953/