A PHP worker that processes a queue, imports data, or performs scheduled background work should run under a service supervisor rather than inside an administrator's terminal session. systemd can start the process at boot, restart it after unexpected exits, apply resource limits, and collect logs. It does not make application code reliable by itself: the worker still needs graceful shutdown, retry handling, and protection against duplicate jobs.
Create a dedicated service identity
Run the worker as a non-login application user with access only to its code and required runtime directories. Keep secrets in a protected environment file or another supported secret mechanism. Do not place credentials directly in a world-readable unit file.
An illustrative unit:
[Unit]
Description=Example PHP Queue Worker
After=network.target
[Service]
Type=simple
User=appworker
Group=appworker
WorkingDirectory=/srv/www/example/current
ExecStart=/usr/bin/php bin/worker.php
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target
Confirm the PHP binary path with command -v php; CLI PHP may differ from the web PHP version. Set environment variables explicitly and use absolute paths.
Install and operate the service
After saving the unit under /etc/systemd/system/example-worker.service, run:
sudo systemctl daemon-reload
sudo systemctl enable --now example-worker
sudo systemctl status example-worker
journalctl -u example-worker -f
Use systemctl restart after a controlled configuration change. Inspect recent logs before repeatedly restarting a failing process.
Design the worker for supervision
Workers should handle SIGTERM, finish or safely release the current job, and exit within the configured stop timeout. Use database transactions or queue visibility timeouts so a crash does not silently lose work. Make job handlers idempotent where possible; a retry may execute a job more than once. Limit memory, execution time, and concurrency according to the workload.
Monitor restart counts and queue age, not only whether the service is “active.” A running worker can still be stuck. On shared hosting, systemd may not be available; use the hosting provider's supported cron or process manager instead of attempting privileged service configuration.