Friday, September 16, 2016

Trapping signals in Docker containers Have you ever stopped a Docker container?

As an example, let’s run the following application (program.js) inside a container and examine signal handlers.
'use strict';
var http = require('http');
var server = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(3000, '0.0.0.0');
console.log('server started');
var signals = {
  'SIGINT': 2,
  'SIGTERM': 15
};
function shutdown(signal, value) {
  server.close(function () {
    console.log('server stopped by ' + signal);
    process.exit(128 + value);
  });
}
Object.keys(signals).forEach(function (signal) {
  process.on(signal, function () {
    shutdown(signal, signals[signal]);
  });
});
Here we create an HTTP-server that listens on port 3000 and setup two signal handlers for SIGINT and SIGTERM. When handled, the following message will be printed to stdout: `server stopped by [SIGNAL]`.

No comments:

Man in the Rain