Running Caddy Server as a service with Upstart

Update: Need to run Caddy as service with systemd? Checkout this blogpost!

Recently I discovered a very promising webserver (written in Go) called Caddy.

Now, Caddy is just an executable, which I wanted to turn into a service on my Ubuntu server.

Upstart

Running any executable as a service can be done using Upstart. Once you’ve created a config file in /etc/init/my_service.conf, you can use some simple commands like service my_service start, service my_service stop, … and the service will run at boot time.

The output of the program will be logged to /var/log/upstart/my_service.log.

Caddy executable

To allow a non-root user to listen on port 80, you must allow the executable to do so:

$ sudo setcap cap_net_bind_service=+ep ./caddy

Config file

My configuration file looks like this:

description "Caddy Server startup script"
author "Mathias Beke"

start on runlevel [2345]
stop on runlevel [016]


setuid some-caddy-user
setgid some-caddy-group

respawn
respawn limit 10 5

limit nofile 4096 4096

script
    cd /home/mathias/
    exec ./caddy
end script

Explanation of the commands:

  • start on runlevel [2245] specifies the job needs to be started after the basic facilities are up.
  • stop on runlevel [016] is used for a normal shutdown.
  • setuid and setgid can be used to run the job under a specific user account. Set this to an account that is less privileged than the root user. You don’t want to run a webserver with root access!
  • respawn will automatically restart (well… ‘respawn’) the process when it stops for any reason.
  • respawn limit COUNT INTERVAL | unlimited specifies a limit for the automatic respawn of the process.

    Respawning is subject to a limit. If the job is respawned more than COUNT times in INTERVAL seconds, it will be considered to be having deeper problems and will be stopped. Default COUNT is 10. Default INTERVAL is 5 seconds.

    To have the job respawn indefinitely, specify an argument of “unlimited”. However, care should be taken using this option: does your service really stop that frequently? Should it?

     Upstart Cookbook

  • exec executes the actual command.