User level systemd
setup - for things like laravel queue workers.
systemd
is mainly used to manage services on modern linux distributions, but it also allows non-root users to manage services running under their own account. This makes systemd
a great alternative to services like supervisord
as it is able to detect crashes and automatically restarts the service.
(1) The directory structure that holds unit files is similar to the systemwide configuration, but is located in a user's home directory:
mkdir -p ~/.config/systemd/user
(2) In this new folder you can create service unit with a .service
extension. A unit is a ini-style file describing a service that has to be managed.
Let's say we have, for example, a Laravel PHP queue worker that we want to be managed by systemd
, called workername.service
, place the lines below in a file named workername.service
:
[Unit]
Description=Laravel PHP queue worker
[Service]
Type=simple
ExecStart=/usr/bin/env php /path/to/my/project/artisan queue:work --sleep=3 --tries=3
RestartSec=10s
Restart=on-failure
[Install]
WantedBy=default.target
(3) Save the above file and then execute to make systemd
recognize your changes:
systemctl --user daemon-reload
(4) You can now manage this service with systemd
:
Starts the service
systemctl --user start workername
Stops the service
systemctl --user stop workername
Restarts the service
systemctl --user restart workername
Status of the service
systemctl --user status workername
(5) If we want this service to start automatically after reboots, we have to enable it:
systemctl --user enable workername
You can also disable a worker using:
systemctl --user disable workername
Everything our PHP script writes to stdout
and stderr
will be recorded by journald
. We can view the logs for this specific service:
journalctl -u workername
Finally if you have more than one service unit you want to setup, you simply follow the same steps above, but name the new worker something unique vs. your existing workers.