node.jsubuntudockersigterm

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.


Solution

  • 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.