Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docker stop doesn't work for node process

I want to be able to run node inside a docker container, and then be able to run docker stop <container>. This should stop the container on SIGTERM rather than timing out and doing a SIGKILL. Unfortunately, I seem to be missing something, and the information I have found seems to contradict other bits.

Here is a test Dockerfile:

FROM ubuntu:14.04
RUN apt-get update && apt-get install -y curl
RUN curl -sSL http://nodejs.org/dist/v0.11.14/node-v0.11.14-linux-x64.tar.gz | tar -xzf -
ADD test.js /
ENTRYPOINT ["/node-v0.11.14-linux-x64/bin/node", "/test.js"]

Here is the test.js referred to in the Dockerfile:

var http = require('http');

var server = http.createServer(function (req, res) {
  console.log('exiting');
  process.exit(0);
}).listen(3333, function (err) {
  console.log('pid is ' + process.pid)
});

I build it like so:

$ docker build -t test .

I run it like so:

$ docker run --name test -p 3333:3333 -d test

Then I run:

$ docker stop test

Whereupon the SIGTERM apparently doesn't work, causing it to timeout 10 seconds later and then die.

I've found that if I start the node task through sh -c then I can kill it with ^C from an interactive (-it) container, but I still can't get docker stop to work. This is contradictory to comments I've read saying sh doesn't pass on the signal, but might agree with other comments I've read saying that PID 1 doesn't get SIGTERM (since it's started via sh, it'll be PID 2).

The end goal is to be able to run docker start -a ... in an upstart job and be able to stop the service and it actually exits the container.

like image 864
sjmeverett Avatar asked Jan 15 '15 18:01

sjmeverett


People also ask

How do I stop a process from running in docker?

To stop a container you use the docker stop command and pass the name of the container and the number of seconds before a container is killed. The default number of seconds the command will wait before the killing is 10 seconds.

How do I force a docker container to stop?

docker rm -f The final option for stopping a running container is to use the --force or -f flag in conjunction with the docker rm command. Typically, docker rm is used to remove an already stopped container, but the use of the -f flag will cause it to first issue a SIGKILL.

How do I stop NPM installing every time docker?

To avoid the npm install phase on every docker build just copy those lines and change the ^/opt/app^ to the location your app lives inside the container. That works.


1 Answers

My way to do this is to catch SIGINT (interrupt signal) in my JavaScript.

process.on('SIGINT', () => {
  console.info("Interrupted");
  process.exit(0);
})

This should do the trick when you press Ctrl+C.

like image 139
Jose Mar Avatar answered Sep 23 '22 10:09

Jose Mar