Simple minimal systemd service setup
Today I spent to much time setting up a simple deamon to start mailcatcher as a systemd service on a ubuntu server acting as a staging server for my Ruby on Rails app.
Since there are enough people and articles on the internet pointing you to comprehensive documentation on how to learn all about systemd, I hope to fill a gap here by writing up how to get done something really simple.
Starting a deamon on ubuntu 16.06(Xenial Xerus).
In my example it was mailcatcher that I wanted to start but it doesn’t really matter. In the current version ubuntu uses a service called systemd to organize services that have to be started on boot etc.
The specs for these services are located at
/etc/systemd/system
For a new service we create a new file there. You should do all this as root by the way (or with sudo)
$> vim /etc/systemd/system/my_service.service
I recommend starting out with something simple as the following:
[Unit]
Description=My new Service
[Service]
Type=simple
ExecStart=/bin/sh -c 'echo "WHAAAAAT" >> /var/log/my_service.log 2>&1'
[Install]
WantedBy=multi-user.target
My research yielded 664 are the correct permissions for such a file, so:
$> chmod 664 /etc/systemd/system/my_service.service
After changing services we have to reload ‘the units’! (- aha!)
$> systemctl daemon-reload
Also before being able to start our service we apparently have to enable it
$> systemctl enable my_service
Now we should be able to actually start it!
$> systemctl start my_service
and we should be able to see the output in the expected log file
$> tail /var/log/my_service.log
WHAAAAAT
Now you can replace ‘echo “WHAAAAAT"’ with whatever executable running your service in foreground, writing to stdout and start it in a way the linux gods approve.
In my case I replaced it with
/home/myuser/.rbenv/shims/mailcatcher --foreground