Laravel: Run Queue in the Background using PM2

To run the Laravel queue, you need to run a command like:

php artisan queue:work --queue=high,medium,low

This is what you can use in your local development environment. But in production, you can not just type this command and keep this running, as soon as you exit your terminal, this command will terminate.

So what to do in this case?

In production, you have to run this command using some process manager to keep the command running. 2 simplest way to do that is using Supervisor or PM2.

I use pm2 in such cases, as this seems simpler to me. Let’s see how to use PM2 for running the Laravel queue in the background

Check Node installation

Make sure you have node installed on your machine. Type the following command in the terminal to check:

# To check node version use the following command
node -v

# To check NPM version use the following command
npm -v

If both commands work, then go to the next step.

Install PM2

The following command will install PM2 globally.

npm install -g pm2

If you face any issue with permission, then include “sudo” at the beginning of the command. Like:

sudo npm install -g pm2

PM2 app/process configuration

Create a file named pm2-queue-worker.yml in the root directory of your Laravel project. This name can be anything, so set the name as you like; just make sure it has a .yml extension.

Now add the following lines in the file:

  - name: my-queue-work
    interpreter: php
    script: artisan
    exec_mode: fork
    instances: 1
      - queue:work
      - --queue=high,medium,low
      - --tries=3
      - --sleep=1

If you prefer to use JavaScript format for configuration, then that can be done too. Follow the documentation from the link –

Run PM2 process

Use the following command to run your worker process:

pm2 run pm2-queue-worker.yml

And done. Your Laravel worker is running in the background now.

If you want to monitor the process, then use commands from the section below:

PM2 process monitoring

  • To check the list of the processes that PM2 is running, use the following command.
pm2 list

This command will show all the processes running using PM2.

Just notice the 2 columns in the table, “App Name” and “id“, you will need that for checking the logs for a specific App.

  • To check PM2 logs (all logs from all Apps), use the following command.
pm2 log
  • To check PM2 logs for a specific app, use the following command. Any of the following commands can be used.
# If your app name is "my-queue-worker"
pm2 log my-queue-worker

# If your app id is 0
pm2 log 0

Or you can use the following command to monitor:

pm2 monit

Finally, use the following documentation for generating the startup script –

Leave a Comment

The reCAPTCHA verification period has expired. Please reload the page.