Set up Caddy with a systemd service

This guide was generated from Claude but I can attest to its accuracy. I'm putting it here in my notes so I can reference these steps next time I make a systemd service.

Creating a systemd Service for Caddy in Ubuntu

Guide for creating a systemd service file for Caddy. This will allow Caddy to run automatically on system boot and be easily managed with systemctl commands.

Here's how to set it up:

  1. Create a new systemd service file:
sudo nano /etc/systemd/system/caddy.service
  1. Add the following content to the file:
[Unit]
Description=Caddy Web Server
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=simple
User=caddy
Group=caddy
ExecStart=/home/caddy/caddy run --config /home/caddy/Caddyfile
ExecReload=/home/caddy/caddy reload --config /home/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target
  1. Create a system user and group for Caddy if it doesn't exist yet:
sudo groupadd --system caddy
sudo useradd --system \
    --gid caddy \
    --create-home \
    --home-dir /home/caddy \
    --shell /usr/sbin/nologin \
    --comment "Caddy web server" \
    caddy
  1. Make sure the Caddy files have the right permissions:
sudo chown -R caddy:caddy /home/caddy
sudo chmod +x /home/caddy/caddy
  1. Reload systemd to recognize the new service:
sudo systemctl daemon-reload
  1. Enable and start the service:
sudo systemctl enable caddy
sudo systemctl start caddy
  1. Check the status to make sure it's running correctly:
sudo systemctl status caddy

Useful systemctl Commands

This setup will have Caddy running as a dedicated system user for better security, and it will automatically start whenever your system boots up.