Skip to content

Instantly share code, notes, and snippets.

@bewithdhanu
Last active May 26, 2025 15:22
Show Gist options
  • Save bewithdhanu/71744c182246e5a3d6d089208b283346 to your computer and use it in GitHub Desktop.
Save bewithdhanu/71744c182246e5a3d6d089208b283346 to your computer and use it in GitHub Desktop.
Bash script to automatically install Supervisor (if not installed), create a Supervisor configuration to run Laravel's queue worker (php artisan queue:work) as the www-data user, and ensure it processes jobs one at a time (no parallel workers). Useful for setting up background job processing in Laravel using the database queue driver.

🔧 Instructions:

  1. Replace /var/www/html and /var/www/your-laravel-app with your real Laravel paths.

  2. Save the script:

    nano setup_laravel_queue.sh
  3. Make it executable:

    chmod +x setup_laravel_queue.sh
  4. Run it with sudo:

    sudo ./setup_laravel_queue.sh
#!/bin/bash
# Define paths and settings
SUPERVISOR_CONF_DIR="/etc/supervisor/conf.d"
APP_NAME="laravel-queue-worker"
QUEUE_COMMAND="php /var/www/html/artisan queue:work --queue=default --sleep=3 --tries=3 --timeout=90"
USER="www-data"
LARAVEL_PATH="/var/www/html"
SUPERVISOR_CONF_FILE="$SUPERVISOR_CONF_DIR/$APP_NAME.conf"
# Function to install Supervisor if not present
install_supervisor_if_missing() {
if ! command -v supervisorctl &> /dev/null; then
echo "Supervisor not found. Installing..."
sudo apt update
sudo apt install -y supervisor
echo "Supervisor installed successfully."
else
echo "Supervisor is already installed."
fi
}
# Function to create Supervisor config
create_supervisor_config() {
echo "Creating Supervisor config at $SUPERVISOR_CONF_FILE..."
sudo bash -c "cat > $SUPERVISOR_CONF_FILE" <<EOL
[program:$APP_NAME]
process_name=%(program_name)s
command=$QUEUE_COMMAND
directory=$LARAVEL_PATH
autostart=true
autorestart=true
user=$USER
numprocs=1
redirect_stderr=true
stdout_logfile=/var/log/supervisor/$APP_NAME.log
stopwaitsecs=3600
EOL
}
# Function to reload and start the supervisor job
start_supervisor_program() {
echo "Reloading Supervisor..."
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start $APP_NAME || echo "Supervisor program may already be running."
}
# Main execution
install_supervisor_if_missing
create_supervisor_config
start_supervisor_program
echo "Laravel queue worker has been configured and started with Supervisor."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment