Run server commands in the background using systemd

When setting up a PHP Laravel application on my web server I needed to run a php command in the background rather than the current terminal session I was using when I connected to my web server.

A tool that can be used for this is systemd which is a library which comes pre-installed with Ubuntu which is the linux distribution I use for all my servers.

How to setup a systemd service

Go to the system folder inside of the systemd directory and you will see all the services that are currently running on the server.

cd /etc/systemd/system

To go to the directory to create your service files chaneg the current diretory to systemd in the lib folder.

cd /lib/systemd/system

Use the touch command to create a blank file with the name representing the command you want to run. For me I want to run a command that runs the Laravel queue so I will name it laravel-queue.service.

sudo touch laravel-queue.service

Use the below content as a template, change the values to the command/s you want to run in your server.

Copy and paste the following content to the file and then save.

[Unit]
Description=Process Laravel app queue

[Service]
ExecStart=/usr/bin/php /var/www/laravel-app/artisan queue:work --tries=3
Restart=on-failure

[Install]
WantedBy=multi-user.target

Here is a list of the values in the above snippet and what each value does.

  • Decription
    • Short text message to describe command
  • ExecStart
    • The command/s to run
  • Restart
    • When to restart the command
  • WantedBy
    • Specify the user who uses command

The service requires enabling, use the systemctl enable command on the service.

sudo systemctl enable laravel-queue.service

After running the enable command a symbolic link will be created, the link will be created inside of the /etc/systemd/system directory which is why it’s best to create the service in another directory instead.

Created symlink /etc/systemd/system/multi-user.target.wants/meshpro-queue.service → /etc/systemd/system/meshpro-queue.service.

The systemd service requires to be restarted to run the new service.

sudo systemctl daemon-reload

Alternative to daemon reload

When I tried the above daemon-reload command the service wasn’t running, an alternative method to getting your service running is to restart the system using the reboot command.

sudo reboot