Sidekiq with environment variables and systemd

Normal setup

Running Sidekiq with systemd is easy, download the sidekiq.service file from Github and place it in /etc/systemd/system.

Start it with: sudo systemctl start sidekiq

Enable it to run at boot: sudo systemctl enable sidekiq

And stop it: sudo systemctl stop sidekiq

The only lines you have to change are:

 

With environment variables

But what if you have some environment variables that you want to load before starting Sidekiq? Keep in mind that there are many ways to do this, and this only how I do it.

I put the environment variables in a hidden file called ‘.env’ in the home directory of the user that runs the application. If this user is called deploy, the file would be /home/deploy/.env

In it are my environment variables with export in front of them:

These are loaded when you log in through ssh with source as the first line in .bashrc. It doesn’t have to be the first line but it has to be above the “if not running interactively don’t do anything” line.

But how do these env variables reach Sidekiq? We’ll simply start Sidekiq with bash in the Systemd service file. Change the ExecStart line in /etc/systemd/system/sidekiq.service and add /bin/bash -lc in front.

Bash will load the environment variables and then start Sidekiq.