我正在开发一个dockerode
用于容器管理的小型应用程序。我正在尝试使进程在docker容器中运行独立于node
进程。
本质上,我要达到的目标是,如果节点进程在重新启动后崩溃,它可以重新附加到正在运行的容器中,然后继续运行,就好像什么都没发生一样。
即使容器本身独立于节点,我遇到的问题也不是容器内的进程,如果节点被杀死,则docker容器中的进程也会被杀死。有没有办法从节点进程中分离容器中的进程?
创建容器并将其重新连接的功能如下:
function createContainer() {
docker.createContainer({
Image: 'ubuntu',
Tty: true,
Cmd: ['/bin/bash']
}, function (err, container) {
if (err) return;
container.start({}, function (err, data) {
const stream = fs.createWriteStream('./containerID.json');
stream.write(JSON.stringify({
containerID: container.id
}));
shell.exec(`docker cp ./script.sh ${container.id}:/`) // copy the file to the container
runExec(container);
});
});
}
exports.containerAttach = (container) => {
container.attach({
stream: true,
stdout: true,
stderr: true
}, function (err, stream) {
stream.pipe(process.stdout);
})
}
该容器最初是使用空闲的BASH Shell创建的。
docker.createContainer({
Image: 'ubuntu',
Tty: true,
Cmd: ['/bin/bash']
},...)
运行附加功能后,它将附加到该空闲TTY。解决方案是切换到docker.run()
然后附加到正在运行的进程。
docker.run('node', ['./home/run-in-container.sh'], false, {
Hostconfig: {
Binds: [`${__dirname}:/home`]
}
}, {}, (err, data, container) => {
if (err) throw err;
console.log(data.StatusCode)
console.log(container)
})
.on('container', (container) => {
setTimeout(() => {
fs.writeFileSync(path.join(__dirname, 'container.json'), JSON.stringify({
id: container.id
}));
process.exit(0);
}, 5000)
})
.on('stream', (stream) => {
stream.on('data', data => console.log('-- STREAM --\n', data.toString()));
})
.on('data', (data) => {
console.log('data', data);
});
Attach函数基本保持不变,但略作修改以匹配新的run函数。
container.attach({
stream: true,
stderr: true,
stdout: true
}, (err, stream) => {
if (err) console.log(`The container has ${container.id} been removed:\n\n${err}`);
console.log(`Reattached to container: ${container.id}`);
stream.on('data', (data) => console.log('-- STREAM --\n', data.toString()));
stream.on('end', () => {
console.log('\n-- STREAM END --')
});
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句