Run Caddy Server as a systemd service

This is how I run my caddy server with systemd on Ubuntu 15.10. There are few changes I have done to recommended configuration.

This assumes few things

  • Your caddy server is located at /opt/caddy/caddy
  • The caddy config file is located at /opt/caddy/conf/main/conf
  • User and Group ‘localsvc’ is present
[Unit]
Description=Caddy webserver
Documentation=https://caddyserver.com/
After=network.target
After=php5-fpm.service

[Service]
TimeoutStartSec=300s
User=localsvc
Group=localsvc
Environment=HOME=/opt/caddy
WorkingDirectory=/opt/caddy
LimitNOFILE=32786
PIDFile=/run/caddy.pid
ExecStart=/opt/caddy/caddy -agree="true" -email="LetsEncryptEmail@email.com" -pidfile="/run/caddy.pid" -conf="/opt/caddy/conf/main.conf" -log="/var/log/caddy/server.log"
ExecStartPre=/bin/chown localsvc:localsvc /var/log/caddy -R
ExecStartPre=/bin/chown localsvc:localsvc /opt/caddy -R
ExecStartPre=/sbin/setcap 'cap_net_bind_service=+ep' /opt/caddy/caddy
Restart=always
StartLimitInterval=600
RestartSec=30
PermissionsStartOnly=true

[Install]
WantedBy=multi-user.target

Few things to note here, first my user ‘localsvc’ does not have a home directory. This is on purose, as this user is not allowed logins. So the following line will set the home folder to the folder in which caddy is installed. This will also cause ‘.caddy’ folder to be created inside the main caddy folder.

Environment=HOME=/opt/caddy

I found that I was having lot of failures due to permission issues, almost all them due to user error. However, permission problems was causing Caddy Server to repeateadly request certificates from LetsEncrypt and quickly exhausting the rate limit. The following two lines made sure I would not have permission problems.

ExecStartPre=/bin/chown localsvc:localsvc /var/log/caddy -R
ExecStartPre=/bin/chown localsvc:localsvc /opt/caddy -R

I also added the following two lines, first one to allow root permission during StartPre and second to allow caddy server to bind to port 80 and 443. Although this only needs to be done once, I found that it was easier to do it here. Takes care of when I upgrade caddy.

PermissionsStartOnly=true
ExecStartPre=/sbin/setcap 'cap_net_bind_service=+ep' /opt/caddy/caddy

Lastly, I set the LimitNOFILE to a higher value as recommended by Caddy Server.

LimitNOFILE=32786