How to reload php-fpm without entering a sudo password

Reloading the php-fpm service is an effective approach of flushing OPcache. The main downside of this approach is that you have to enter your sudo password to reload the service. Automated deployment scripts will get stuck on the password prompt, and fail.

This post will explain how to reload php-fpm without being prompted for your sudo password.

Visudo and the sudoers file

The visudo command is a safe way to edit the sudoers file. The sudoers file allows you to define commands that any user can run as root without having to enter a password. You'll need sudo rights to run the visudo command.

To add php-fpm to the sudoers file, run:

sudo visudo

Then add this line to bottom of the file. Make sure to change "sjorso" with the name of your user.

sjorso ALL=(ALL) NOPASSWD: /usr/sbin/service php*.*-fpm reload

Note that this line contains a wildcard php*.*-fpm. This allows you to flush any version of php-fpm with a single command. You can flush php7.4-fpm, php8.0-fpm, and in the future php8.1-fpm without having to edit the sudoers file again.

Reloading php-fpm

After you've edited the sudoers file, you can now reload the php-fpm service without entering a password using the following command:

echo "" | sudo -S service php*.*-fpm reload

Why echo "" | sudo ...?

The "echo + pipe + sudo" is a trick that causes the command to fail instantly if a sudo password is required. This is useful if the visudo whitelist is misconfigured. Without the echo, when prompted for a password, the script will try to use the next three commands as the password. This can have unexpected consequences.

A picture of me

Hi, I'm Sjors 👋

I write about Laravel, web development, and other technical topics. You can follow me on twitter if you want to stay up-to-date on the things I'm doing.

If you want to get in touch, you can email me at sjorsottjes@gmail.com