Is it possible to shut down the host machine by executing a command on one of its docker container?

前端 未结 1 1139
青春惊慌失措
青春惊慌失措 2020-12-17 01:30

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 conta

相关标签:
1条回答
  • 2020-12-17 02:09

    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.

    0 讨论(0)
提交回复
热议问题