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.

  1. Docker Compose. If all the dependencies of your container can run in other containers, then you can create a docker-compose.yml file with all the containers you need to run and use the depends_on option 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.
  2. 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.target

A 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.

  1. systemd.unit
  2. 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.

  1. Wants=postgresql@19-main.service. This option means that Postgres will be started when myapp is started. However, myapp will start even if Postgres fails to start. This gives myapp the opportunity to start in a degraded state.
  2. After=postgresql@19-main.service. This option indicates that when Postgres starts successfully, myapp starts after Postgres. Without this option, running systemctl start myapp.service will start both myapp and Postgres simultaneously.

For the strong dependency on Docker, we use the following options.

  1. BindsTo=docker.service. This option tells systemd to start Docker when myapp is started. This option also tells systemd to stop myapp when Docker is manually stopped by systemctl stop docker.service or when Docker crashes. This option also tells systemd to restart myapp when we do systemctl restart docker.service. All these behaviors guarantee that the status of myapp reported by systemctl status myapp.service is accurate because myapp cannot run without Docker.
  2. After=docker.service. This option together with BindsTo= ensures that all reasons that make Docker out-of-service also make myapp stop. Option BindsTo= by itself does not cover situations where systemd refuses to start Docker or “skips” it because some Condition...= option on docker.service was unmet.

Start on system start

We tell systemd to start myapp on boot in two steps.

  1. We use the option WantedBy=multi-user.target. This tells systemd to add a Wants= dependency from multi-user.target to myapp. It is as if we had written Wants=myapp.service in the unit file for multi-user.target. On boot, systemd starts all the dependencies of multi-user.target.
  2. 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.

  1. Startup options.

    1. ExecStartPre=-/usr/bin/docker rm --force %n. This is a command that runs before the container for myapp runs, so it is a way to ensure that we remove any previous container. With this option we tell systemd to run docker rm --force myapp.service. The %n is replaced by the full unit name myapp.service and 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).

    2. ExecStart=.... With this option we indicate the command to run the main process of the service. Several things happen here.

      1. 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, like docker run --detach ....

      2. The Docker CLI runs as user myapp. As a general rule, it is a good practice to give services their own user, so we use sudo -u myapp docker run ... to run docker run ... as user myapp on the host machine. This is even more important in our example because myapp happens to have access to the Docker service in the host machine via the volume mount for /var/run/docker.sock.

      3. 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 to ExecStart=.... For example, we define variable ${PORT} in /etc/myapp/env along with other variables for the service. We also pass the same file to the environment of container myapp so that myapp uses the same value for ${PORT}.

    3. Type=simple. This option tells systemd that myapp is a simple service that does not signal that it has started successfully, so systemd should consider myapp.service started 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 on myapp by means of After=myapp.service can start as soon as myapp.service starts, which might not be what you want.

  2. Recovery options.

    1. 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.

    2. RestartSec=15. This is how many seconds to wait before restarting the service after the service stops.

  3. Stop options.

    1. ExecStop=/usr/bin/docker stop %n. Without this option, systemd would stop the main process of the service by sending it signal SIGTERM. With this option, systemd uses docker stop myapp.service to 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.

    2. 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 container myapp.service is not left behind, so we do docker 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.

  1. Make sure the unit file is in the right location. The unit file should be located in /etc/systemd/system/myapp.service.
  2. Tell systemd to load the file. For this, run systemctl daemon-reload. The command finds and reloads all unit files.
  3. 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.
  4. Start the service. Run the command systemctl start myapp.service. It is possible to run this command without running enable first, but without enable the service will not start on boot.

Comments