Why do systemd unit examples use docker start/stop/kill instead of docker run --rm?
All of the systemd unit file examples in the documentation use a combination of ExecStartPre, ExecStart, and ExecStop commands to control the Docker container lifecycle. For example, on https://coreos.com/docs/launching-containers/launching/launching-containers-fleet/:
[Unit]
Description=MyApp
After=docker.service
Requires=docker.service
[Service]
TimeoutStartSec=0
ExecStartPre=-/usr/bin/docker kill busybox1
ExecStartPre=-/usr/bin/docker rm busybox1
ExecStartPre=/usr/bin/docker pull busybox
ExecStart=/usr/bin/docker run --name busybox1 busybox /bin/sh -c "while true; do echo Hello World; sleep 1; done"
ExecStop=/usr/bin/docker stop busybox1
It's never explained why it's necessary (or recommended) to split the container lifecycle into separate commands instead of replacing all of these with ExecStart=/usr/bin/docker run --rm ..., which will remove the container automatically when the process ends.
If someone just answers the question here, I'd be happy to open a PR to add it to the docs somewhere. Thanks!
If a container fails, you may not want it removed immediately in order to perform diagnostics. This is why the container is simply stopped (via docker stop) rather than stopped and removed.
Additionally, the --rm feature is implemented by the client -- in other words, if the client were to exit unexpectedly, the container would not get cleaned up in any case (and even if --rm were implemented by the server, you still wouldn't want that because of the previous reason).
Why do the ExecStartPre commands start with a "-" ? Whereas ExecStart does not? e.g. ExecStartPre=-/usr/bin/docker ... ExecStart=/usr/bin/docker run ...
man systemd.service:
If the absolute filename is prefixed with "-", an exit code of the command normally considered a failure (i.e. non-zero exit status or abnormal exit due to signal) is ignored and considered success.
The kill and rm will obviously fail if the container does not exist. You want systemd to ignore those errors.
Ahh that would explain why docker unit was not starting up. Thanks