DEV Community

Krishnan
Krishnan

Posted on • Edited on

Running a PHP script or Worker as a Systemd Service

Systemd is one of the best ways to run a PHP script as a service or to configure a worker. I have used it to configure multiple workers on the same server and it works seamlessly. You do not need to install, supervisor anymore to run your workers.

In this article I have covered the step by step process to configure a service on Linux.

Step 1: Choose a name for your service. Choose the name in relation to the application or the use case so that you remember it in the future.

Step 2: Create a service file with the chosen name.

sudo touch /etc/systemd/system/worker-name-service.service
Enter fullscreen mode Exit fullscreen mode

Step 3: Edit the file and add the service information to it and save the file.

sudo nano /etc/systemd/system/worker-name-service.service
Enter fullscreen mode Exit fullscreen mode
[Unit]
Description=My App Notification Worker
After=network.target

[Service]
User=root
Group=www-data
Restart=always
WorkingDirectory=/var/www/html/path-to-worker
ExecStart=/usr/bin/php artisan queue:work

[Install]
WantedBy=multi-user.target
Enter fullscreen mode Exit fullscreen mode

Step 4: Reload the systemd daemon so that the new service is recognised.

sudo systemctl daemon-reload
Enter fullscreen mode Exit fullscreen mode

Step 5: Enable the new service.

sudo systemctl enable worker-name-service
Enter fullscreen mode Exit fullscreen mode

Step 6: Start the new service.

sudo systemctl start worker-name-service
Enter fullscreen mode Exit fullscreen mode

Step 7: Check the status of the service to ensure it is up and running.

sudo systemctl status worker-name-service
Enter fullscreen mode Exit fullscreen mode

If you see the green light then you have successfully configured your worker or php script as a systemd service.

Originally posted on my personal blog.

Top comments (0)