ProTip: Run a Docker container as a systemd service
Did you know that Docker has a convenient option for keeping a container running across system restarts? It is called --restart unless-stopped. What this option does not offer is a way to control when your container starts after a system reboot, so we explain a way to do this.
There are a couple of options for controlling the startup order of containers.
- Docker Compose. If all the dependencies of your container can
run in other containers, then you can create a
docker-compose.ymlfile with all the containers you need to run and use thedepends_onoption to indicate that a given container depends on another. However, there is no way to indicate the startup order relative to system services running on the host. - Service Manager. If what you need is to ensure that your container starts after a host service, like a database, or even that other host services that depend on your container run only after your container is up, then running your container using the host’s service manager is the way to go.
In this post we explain the service manager approach because it seems to be the lesser-known of the two.
Example unit file
We walk through an example of running a container as a host service on
Ubuntu using the service manager systemd. The
final result is the following unit file for an app called myapp.
[Unit]
Description=myapp
BindsTo=docker.service
After=docker.service
Wants=postgresql@19-main.service
After=postgresql@19-main.service
[Service]
EnvironmentFile=/etc/myapp/env
ExecStartPre=-/usr/bin/docker rm --force %n
ExecStart=/usr/bin/sudo -u myapp \
/usr/bin/docker run \
--env-file /etc/myapp/env \
--publish ${PORT}:${PORT} \
--volume /var/run/docker.sock:/var/run/docker.sock \
--volume /var/run/postgresql:/var/run/postgresql \
--name %n \
myapp:latest
ExecStop=/usr/bin/docker stop %n
ExecStopPost=/usr/bin/docker rm --force %n
Restart=always
RestartSec=15
Type=simple
[Install]
WantedBy=multi-user.targetA note for the self-taught. We try to explain just enough to understand this unit file but systemd is nuanced and if at any point something does not work or make sense, you should refer to the documentation. The systemd documentation that explains what this file means is the following. You can access it online or directly from your terminal.
systemd.unit- Online: https://www.freedesktop.org/software/systemd/man/latest/systemd.unit.html
- Terminal:
man systemd.unit
systemd.service- Online: https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#
- Terminal:
man systemd.service
Example step-by-step
File location
The location of the sample file is
/etc/systemd/system/myapp.service. The directory
/etc/systemd/system/ is one of the directories in the load path of
systemd. The extension indicates that this is a unit file for a
service.
systemd can also manage other kinds of resources, like
timers
(similar to cron jobs, but used to schedule systemd services) and
mount
points.
For example,
certbot,
the tool that automates the renewal of Let’s Encrypt TLS
certificates, uses service, mount and timer
systemd units to do its thing.
Start order
The app myapp depends on Docker and Postgres in different ways. App
myapp could run in a degraded state when Postgres fails to start or
dies. In that case, myapp could simply show an error page. However,
myapp would not be able to run at all if Docker did not start or
failed. So for that reason we indicate the dependencies in the
following way.
For the weak dependency on Postgres, we use the following options.
Wants=postgresql@19-main.service. This option means that Postgres will be started whenmyappis started. However,myappwill start even if Postgres fails to start. This givesmyappthe opportunity to start in a degraded state.After=postgresql@19-main.service. This option indicates that when Postgres starts successfully,myappstarts after Postgres. Without this option, runningsystemctl start myapp.servicewill start bothmyappand Postgres simultaneously.
For the strong dependency on Docker, we use the following options.
BindsTo=docker.service. This option tells systemd to start Docker whenmyappis started. This option also tells systemd to stopmyappwhen Docker is manually stopped bysystemctl stop docker.serviceor when Docker crashes. This option also tells systemd to restartmyappwhen we dosystemctl restart docker.service. All these behaviors guarantee that the status ofmyappreported bysystemctl status myapp.serviceis accurate becausemyappcannot run without Docker.After=docker.service. This option together withBindsTo=ensures that all reasons that make Docker out-of-service also makemyappstop. OptionBindsTo=by itself does not cover situations where systemd refuses to start Docker or “skips” it because someCondition...=option ondocker.servicewas unmet.
Start on system start
We tell systemd to start myapp on boot in two steps.
- We use the option
WantedBy=multi-user.target. This tells systemd to add aWants=dependency frommulti-user.targettomyapp. It is as if we had writtenWants=myapp.servicein the unit file formulti-user.target. On boot, systemd starts all the dependencies ofmulti-user.target. - We apply that option by running
systemctl enable myapp.service.
Management of container lifecycle
Everything in section [Service] of our unit file controls the
lifecycle of the container for myapp.
-
Startup options.
-
ExecStartPre=-/usr/bin/docker rm --force %n. This is a command that runs before the container formyappruns, so it is a way to ensure that we remove any previous container. With this option we tell systemd to rundocker rm --force myapp.service. The%nis replaced by the full unit namemyapp.serviceand the minus symbol after the equals sign makes systemd ignore error exit codes from the command (docker rm --force ...does return a non-zero exit code if the container is not found). -
ExecStart=.... With this option we indicate the command to run the main process of the service. Several things happen here.-
The service is a long-running process. The command
docker run ...embodies the service and it runs until the app container exits. This is different from, let’s say, a command that returns immediately after forking or leaving another process behind, likedocker run --detach .... -
The Docker CLI runs as user
myapp. As a general rule, it is a good practice to give services their own user, so we usesudo -u myapp docker run ...to rundocker run ...as usermyappon the host machine. This is even more important in our example becausemyapphappens to have access to the Docker service in the host machine via the volume mount for/var/run/docker.sock. -
The command uses environment variables defined by option
EnvironmentFile=/etc/myapp/env. The option loads a text file consisting of newline-separated environment variable assignments and makes those variables available toExecStart=.... For example, we define variable${PORT}in/etc/myapp/envalong with other variables for the service. We also pass the same file to the environment of containermyappso thatmyappuses the same value for${PORT}.
-
-
Type=simple. This option tells systemd thatmyappis a simple service that does not signal that it has started successfully, so systemd should considermyapp.servicestarted as soon as the main process runs. Then, the service is considered running as long as the main process is running. It is possible to make systemd monitor the health of a service and take action with other values for this option, this is only a basic example. One important caveat is that any service depending onmyappby means ofAfter=myapp.servicecan start as soon asmyapp.servicestarts, which might not be what you want.
-
-
Recovery options.
-
Restart=always. This option tells systemd to restart the service if the main command is killed or exits regardless of the status code. As this is only an example, this is a basic restart policy and it may result in a crashloop if you are not careful. We also do not mix this option with a Docker restart policy so that systemd accurately tracks the state of the container. -
RestartSec=15. This is how many seconds to wait before restarting the service after the service stops.
-
-
Stop options.
-
ExecStop=/usr/bin/docker stop %n. Without this option, systemd would stop the main process of the service by sending it signalSIGTERM. With this option, systemd usesdocker stop myapp.serviceto stop the service. One important thing to keep in mind is that the command you indicate with this option must wait for the main process to terminate. Otherwise, systemd will try to kill the main process and therefore your service might not stop cleanly. -
ExecStopPost=/usr/bin/docker rm --force %n. This is a cleanup command that is executed when the service is terminated or stops, regardless of status code. It is also invoked when the service fails to start up correctly. In our example, we just want to make sure that the containermyapp.serviceis not left behind, so we dodocker rm --force myapp.service.
-
Final steps: installation and service startup
Now that we understand the unit file, we install it and start the service as follows.
- Make sure the unit file is in the right location. The unit file
should be located in
/etc/systemd/system/myapp.service. - Tell systemd to load the file. For this, run
systemctl daemon-reload. The command finds and reloads all unit files. - Tell systemd that it can start the service on boot. We do so by
running
systemctl enable myapp.service. This command then applies the options in the[Install]section of the unit file. - Start the service. Run the command
systemctl start myapp.service. It is possible to run this command without runningenablefirst, but withoutenablethe service will not start on boot.