Node.js 对Docker容器的清理
我希望有一个运行nodejs和socket.io的多docker容器设置。 我正在使用redis进行一些共享socketId/state。当我杀死一个nodejs进程时,我会执行一个cleanup函数来删除该进程附带的sockeId/状态Node.js 对Docker容器的清理,node.js,redis,docker,socket.io,Node.js,Redis,Docker,Socket.io,我希望有一个运行nodejs和socket.io的多docker容器设置。 我正在使用redis进行一些共享socketId/state。当我杀死一个nodejs进程时,我会执行一个cleanup函数来删除该进程附带的sockeId/状态 process.stdin.resume();//so the program will not close instantly function exitHandler(options, err) { console.log('exitHandler')
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}));
当节点未在容器中运行时,这一点非常有效。当它在一个容器中并且我杀死了这个容器时,清理就不会执行。我想在我清理之前,容器已经把所有的通讯管道都弄坏了。有没有办法解决这个问题 您需要收听
SIGTERM
。当您运行docker-stop
时,它将向容器发送SIGTERM
,并等待10秒。如果容器没有同时停止,它将向内核发送一个SIGKILL
,以完成容器
推荐参考:
因此,从容器内部,您应该监听
SIGTERM
。从外部,您可以使用docker API检查您的容器是否被杀死,并执行正确的工作:您可以尝试外部心跳控制。您能否详细说明我是docker上的新手的想法/过程?您需要一个监控容器,监视您的工人,并且每当有人退出时,进行清理。当容器关闭时,docker守护进程本身也会触发一些事件。如果有帮助,我可以解释更多是的,我需要在node.js过程中得到通知。为什么process.on('SIGINT',exitHandler.bind(null,{exit:true}));不履行职责?你知道我应该听什么节目吗?