Running docker containers with systemd

Created at
22 June 2026
Last modified
22 June 2026
Status
🌿 sapling
Tagged
Node map

You can run docker containers automatically, but you get a bit more control if you run them through systemd. Here's a blog post on it.

Here's the unit file they recommend:

# /etc/systemd/system/myapp.service

# Manages the main web application Docker container

[Unit]
Description=MyApp Web Application
Documentation=https://docs.myapp.com
After=docker.service
Requires=docker.service
Wants=network-online.target
After=network-online.target
StartLimitIntervalSec=300
StartLimitBurst=5

[Service]
# Container lifecycle management
Type=simple
Restart=on-failure
RestartSec=15

# Environment file for sensitive configuration
EnvironmentFile=/etc/myapp/env

# Clean up any leftover container from a previous run
ExecStartPre=-/usr/bin/docker stop myapp
ExecStartPre=-/usr/bin/docker rm myapp
ExecStartPre=/usr/bin/docker pull myapp:${VERSION}

# Run the container in the foreground
ExecStart=/usr/bin/docker run \
  --name myapp \
  --rm \
  -p 8080:8080 \
  --env-file /etc/myapp/env \
  --log-driver=journald \
  --log-opt tag=myapp \
  -v /data/myapp:/app/data \
  myapp:${VERSION}

# Stop the container gracefully
ExecStop=/usr/bin/docker stop -t 30 myapp

# How long to wait for the stop command
TimeoutStartSec=120
TimeoutStopSec=45

[Install]
WantedBy=multi-user.target

Some thigns worth noting:

  • This needs docker to be running (Requires=docker.service), and wanted the network to be running (Wants=network-oneline.target). It'll run even if the network isn't online, however.