Manage Puma + Sidekiq services with rbenv + systemd on Ubuntu 16.04

How to manage Puma and Sidekiq as services using Systemd for Ruby on Rails apps

Systemd services for Puma and Sidekiq

As you may know, Debian did switch to systemd, so Ubuntu ended up switching too.

The version Ubuntu 16.04 (Xenial Xerus) uses systemd as default init system, so you will probably have to deal with it sooner or later on Ubuntu ecosystem, unless you decide to remove it and bring back the upstart, it is possible but will not be covered on this article.

This is a simple how to configure services for Puma web server and Sidekiq background processor when using rbenv as ruby manager.

I will assume you have all setup and can run your app manually.

Unit

Units are any resource that the operating system will manage, it is made through unit files. We are gonna have a puma unit and a sidekiq unit.

Puma unit

The puma unit file should goes on:

/etc/systemd/system

Considering the user to be used is deploy and the app runs on /var/www/[app_path]/current, the content can be like:

[Unit]
Description=Puma HTTP Server
After=network.target

[Service]
Type=simple

User=deploy

WorkingDirectory=/var/www/[app_path]/current

EnvironmentFile=/etc/environment
ExecStart=/home/deploy/.rbenv/bin/rbenv exec bundle exec puma -C config/puma.rb

Restart=always

[Install]
WantedBy=multi-user.target

Sidekiq unit

The sidekiq unit file goes on the same place:

/etc/systemd/system

Again, considering the user to be used is deploy and the app runs on /var/www/[app_path]/current, the content can be like:

[Unit]
Description=Sidekiq workers
After=network.target

[Service]
Type=simple

User=deploy

WorkingDirectory=/var/www/[app_path]/current

EnvironmentFile=/etc/environment
ExecStart=/home/deploy/.rbenv/bin/rbenv exec bundle exec sidekiq -C config/sidekiq.yml -e production

Restart=always

[Install]
WantedBy=multi-user.target

Config files

Note that puma unit will look for config/puma.rb as config, also sidekiq unit will look for config/sidekiq.yml.

Make sure both configuration files are on the same path, or change it to the path where you put your config files.

For this example, the config files are on the same path of the app itself.

I made a gist with both, unit and config files, you can find it here:

https://gist.github.com/renatonitta/354d683ea35fc96bd6d23ea88e6884e1

Enable services to init on system startup

Use the systemctl command to enable the services:

sudo systemctl enable puma.service
sudo systemctl enable sidekiq.service

This should create a symlink in /etc/systemd/system/multi-user.target.wants/, and will enable automatic starting after a reboot.

Reload the systemd daemon and services

sudo systemctl daemon-reload
sudo systemctl restart puma.service
sudo systemctl restart sidekiq.service

Now you can reboot the machine to test if all is working properly.

sudo reboot