I supervise my SCB “services” with systemd. When I wanted to containerize the underlying processes, I had a fair bit of trouble tracking down a simple approach. This method has no dependencies–thought I’d share it.
File: /etc/systemd/system/docker.foobar.service
[Unit]
Description=Docker FooBar Service
After=docker.service
Requires=docker.service
[Service]
Environment="AN_ENVIRONMENT_VARIABLE=42"
# Long startup timeout to support an image-pull.
TimeoutStartSec=600
Restart=always
ExecStartPre=-/usr/bin/docker rm -f %n
ExecStartPre=/usr/bin/docker pull foobar:latest
ExecStart=/usr/bin/docker run \
--name %n \
-e AN_ENVIRONMENT_VARIABLE \
-e HOST_MACHINE_HOSTNAME=%H \
foobar:latest
ExecStop=/usr/bin/docker kill --signal=SIGINT %n
[Install]
WantedBy=default.target
Usage:
# Enable it (so it starts on system startup
$ sudo systemctl enable docker.foobar
# Restart it (as you might do when you want to pull the newest `:latest`
$ sudo systemctl restart docker.foobar
# View its logs
$ sudo journalctl -u docker.foobar
Footnotes
- The
-
before the ExecStartPre indicates to systemd that the startup should continue even if this exits non-zero - %n is the service name, in this case docker.foobar.service
- AN_ENVIRONMENT_VARIABLE is defined in the supervised process (host machine), the -e AN_ENVIRONMENT_VARIABLE in the Docker invocation shares that environment variable with the container.
- HOST_MACHINE_HOSTNAME is explicitly passed into the Docker container
PS This file’s footprint will be smaller with a daemonless container runtime. Podman, one of the frontrunners in that effort, is first-class supported in Debian Bullseye. When that’s considered stable-for-newbs, I’ll come back and update this.