I would like to shutdown the machine (host) when the docker container finishes a job.
My host OS is Ubuntu.
The container can run as --privileged=true. That is not a problem.
I managed to do this with the command (found in a stackoverflow answer):
subprocess.run("echo 1 > /proc/sys/kernel/sysrq; echo o > /proc/sysrq-trigger", shell=True, check=True)
The problem with this approach it is immediate, unclean shutdown in Linux.
If I try a clean way as a shutdown now, I get the following error: System has not been booted with systemd as init system (PID 1). Can't operate.
How can I use shutdown or halt or other alternative within my container to shutdown the host?
For your specific case to perform a shutdown once the docker exits mikey's solution is simple and elegant.
For a more generic case, like with a bunch of dockerized micro-services with one needing to be able to shut down or reboot the host, the following approach can be used:
In systemd systems like recent Debian or Ubuntu, the
shutdown/halt/poweroff/rebootcommands are just symlinks tosystemctland it is possible to run for examplesystemctl haltinstead of justhalt.So the issue becomes to perform
systemctlcommands on the host from within a docker container. This can be achieved mapping some volumes like in the following command:With these volumes mapped, you can then just execute a
systemctl powerofffrom within the docker and the host will shut down and power off.