Is it possible to shut down the host machine by ex

2019-04-11 18:20发布

问题:

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!

回答1:

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.

An Interface

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.

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.

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

You could poll the file if inotifywait is not available.

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

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.



回答2:

Have you tried this?

sudo docker rm -v container
sudo shutdown


标签: docker