使用Docker运行单个NodeJS脚本并能够使用Ctrl-C终止它的最简单方法是什么 [英] What is the easiest way to run a single NodeJS script using Docker and be able to terminate it with Ctrl-C

查看:183
本文介绍了使用Docker运行单个NodeJS脚本并能够使用Ctrl-C终止它的最简单方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从Docker文档中得出的结论是,如果您要运行独立的NodeJS脚本,则应使用以下命令:

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- --rm --name my-running-script -v $ PWD:/ usr / src / app -w / usr / src / app node:8节点your-daemon-or-script.js

除了无法使用Ctrl-C停止脚本外,此方法有效。我该如何实现?

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

这是我的script.js:

Here is my script.js:

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

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


推荐答案

此注释隐藏在扩展了 docker run 文档

This note is hidden in the extended docker run documentation:


注意: Linux会特别对待在容器内以PID 1运行的进程:默认操作会忽略任何信号。因此,除非经过编码,否则该过程不会在 SIGINT SIGTERM 上终止。

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.

主要Docker容器进程(您容器的 ENTRYPOINT CMD 或在命令行上指定的等效项)在容器内作为进程ID 1运行。通常,这是为特殊的init进程保留的,并且在某些方面是特殊的。

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.

可能最简单的答案是让Docker为您注入一个PID为PID的init进程。通过在 docker run 命令中添加-init

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.

或者,您可以在Node上注册信号事件显式处理 SIGINT 。例如,如果我将您的脚本扩展为具有

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();
});

然后重建图像并重新运行它,它响应^ C。

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

这篇关于使用Docker运行单个NodeJS脚本并能够使用Ctrl-C终止它的最简单方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆