在Docker容器上清理

我希望有一个多docker容器设置运行nodejs与socket.io。 我正在使用Redis的一些共享socketId /状态。 当我杀死一个nodejs进程时,我执行了一个清除函数来删除与进程相关的sockeId /状态。

process.stdin.resume();//so the program will not close instantly function exitHandler(options, err) { console.log('exitHandler'); _.forEach(global.sockets, (socket)=> { if (global.redisClient) { global.redisClient.hdel('socketA', socket); global.redisClient.hdel('socketB', socket); global.redisClient.del(`socketC_${socket}`); } }); _.forEach(global.userIds, (userId)=> { if (global.redisClient) { global.redisClient.hdel('socketD', userId); global.redisClient.del(`socketE_${userId}`); } }); if (options.cleanup) console.log('clean'); if (err) console.log(err.stack); if (options.exit) process.exit(); } //do something when app is closing process.on('exit', exitHandler.bind(null, {cleanup: true})); //catches ctrl+c event process.on('SIGINT', exitHandler.bind(null, {exit: true})); //catches uncaught exceptions process.on('uncaughtException', exitHandler.bind(null, {exit: true})); 

当节点不在容器中运行时,这很好。 当它在一个容器中,我杀了容器清理不执行。 我想这个容器在我可以清理之前正在杀死所有的通讯pipe道。 有想法该怎么解决这个吗 ?

你需要听SIGTERM 。 当你运行docker stop <container> ,它会发送一个SIGTERM到容器并等待10秒钟。 如果容器不停止,它会向内核发送一个SIGKILL来完成容器。

推荐参考: 优雅地停止Docker容器

所以,从容器里面,你应该听SIGTERM 。 从外部,您可以使用docker API来检查您的容器是否被杀死,并执行正确的工作: 监控Docker事件