是否可以通过在其Docker容器之一上执行命令来关闭主机? [英] Is it possible to shut down the host machine by executing a command on one of its docker container?

查看:152
本文介绍了是否可以通过在其Docker容器之一上执行命令来关闭主机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台具有一个docker容器的主机。容器处于活动状态并正在运行特定服务。在满足特定条件时,我想卸下容器并关闭机器。有可能这样做吗?
我打算修改运行该服务的代码来处理机器的关闭问题?欢迎任何建议!

I have a host machine which has one docker container. The container is active and running a particular service. On meeting a particular condition, I want to remove the container and shut down the machine also. Is it possible to do so? I am planning to modify the code which runs the service to handle the shutting down of the machine? Any suggestions are welcome!

推荐答案

运行干净关机将取决于主机初始化系统。

Running a clean shutdown will be dependent on the hosts init system.

为避免授予容器具有特权的访问权限,并且还避免在容器中安装主机特定的初始化工具,您可以创建一个接口来通知主机关闭,而不是尝试让容器运行关闭。

To avoid giving the container --privileged access and to also avoid installing host specific init tools in your container, you could create an interface to signal the host to shutdown rather than the trying to get the container to run the shutdown.

有很多方法可以完成。一个简单的起点可以是已安装的卷,可以在容器和主机之间共享数据。现在可以使用文件,但是您可以使用套接字,fifo,TCP或所需的任何其他IPC方法。

There's many ways this could be done. A simple starting point could be a mounted volume to share data between the container and host. A file will do for now but you could use a socket, fifo, TCP or any other IPC method you want.

在主机上创建一个文件,例如 / var / run / shutdown_signal 并将文件装入容器中

Create a file on the host, say /var/run/shutdown_signal and mount the file into your container

docker run -d -v /var/run/shutdown_signal:/shutdown_signal whatever 

当您希望主机关闭时,将字符串写入文件中

Write a string into the file when you want the host to shutdown

docker exec $cid sh -c 'echo true > /shutdown_signal'

然后,您需要在主机上运行某些东西来监视文件。

Then you need something running on the host to monitor the file.

一个简单的脚本,使用 inotifywait 等待文件更改。

A simple script that waits for file changes with inotifywait.

echo "waiting" > /var/run/shutdown_signal
while inotifywait -e close_write /var/run/shutdown_signal; do 
  signal=$(cat /var/run/shutdown_signal)
  if [ "$signal" == "true" ]; then 
    echo "done" > /var/run/shutdown_signal
    shutdown -h now
  fi
done

如果 inotifywait 不可用,则可以轮询文件。

You could poll the file if inotifywait is not available.

while sleep 30; do
  signal=$(cat /var/run/shutdown_signal)
  ...



可怕的选择



还有一种更通用的内核方法可以在Linux中触发立即不干净的关机。

The Horrible Alternative

There is also a more universal, kernel way to trigger an immediate, unclean shutdown in Linux.

docker run --privileged busybox \
  sh -c 'echo 1 > /proc/sys/kernel/sysrq; echo o > /proc/sysrq-trigger'

但这可能会给您带来更多的问题,而不是值得的。

But this will likely cause more issues for you than it's worth.

这篇关于是否可以通过在其Docker容器之一上执行命令来关闭主机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆