Out of the box, if you want to restart your app after a server reboot, you can just run
$ mix edeliver restart production
in a terminal from your local app directory.
Having to run this command after every reboot is a minor annoyance, but, what if your hosting company decides to restart your server in the middle of the night? What if you have many elixir apps running on the same server? What if you’re just OCD about never wanting to type commands again and just want the damn thing automated? Well, one way to solve that requires a systemd service.
Starting and Stopping Your App from the Server Itself
Edeliver uses another great tool, Distillery, to help build releases, and Distillery provides several useful command line tasks, including tasks that start and stop your app. This is what we’ll use in our systemd script.
NOTE: This article assumes you have setup your deployment process the same way as this article.
Step 1: Create a Systemd Unit File
We need to create a .service file that will run on restart in systemd’s system directory. Since we’re on Ubuntu 16.04, the directory we’re looking for is at /etc/systemd/system, but depending on your OS it might be /usr/lib/systemd/system or /lib/systemd/system. Regardless, you now need to create a file in that directory called your_app.service with the following contents:
Step 2: Check the syntax
After you’ve saved the unit file, verify its syntax with the command:
$ sudo systemd-analyze verify /etc/systemd/system/your_app.service
If all is well, the command returns nothing, otherwise it will tell you where it encountered an error.
Step 3: Enable the service
You can enable and start your new service with the following commands:
$ sudo systemctl enable your_app
$ sudo systemctl start your_app
And that’s it! If you do a server reboot now, your app should automatically back up and running!