Linux – Start PHP-FPM with root option automatically

init.dlinuxphp-fpmphp7root

I was trying to get PHP-FPM running a pool as root, but I can't seem to adjust the init.d startup params.

It works when starting PHP-FPM from the CLI (with sudo php-fpm7.0 -DRy /etc/php/7.0/fpm/php-fpm.conf, but I can't get this to work with the service command (sudo service php7.0-fpm (re)start. So Everytime the server reboots, PHP-FPM fails and I would have to run this command.

I have tried to place a file "php-fpm7.0" in /etc/default with the line DAEMON_ARGS="--daemonize --fpm-config $CONFFILE -R", and I even tried add the -R parameter to the do_start function in /etc/init.d/php7.0-fpm directly, but I keep getting the please specify user and group other than root error.

Is there any way I can get this working on startup and with the service command?


Off topic: I know all the risks and I know why I shouldn't do it, but I want to anyway. I need to run some scripts to create directories, performing chown commands etc. and the pool will be dedicated to a backend used by an nginx server block which is reachable from within the private 192.168.1.X network only on one specific URL path.

As an alternative I could set up a cron script which executes a PHP script as root, but that approach would cost me a lot more hours.

Best Answer

On systemd systems, you may have to configure this via systemd rather than system V init scripts

The below steps are tested and working on Ubuntu 16.04 LTS. And this is your culprit for redirected init scripts:

/lib/lsb/init-functions.d/40-systemd

1. Edit your php-fpm pool configuration e.g. /etc/php/7.0/fpm/pool.d/www.conf and configure root as the user/group as root

; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
;       will be used.
user = root
group = root

2. Edit /lib/systemd/system/php7.0-fpm.service and append -R to the ExecStart variable to allow the service to run as root

ExecStart=/usr/sbin/php-fpm7.0 --nodaemonize --fpm-config /etc/php/7.0/fpm/php-fpm.conf -R

3. Reload the configuration

$ systemctl daemon-reload

4. Start the service

$ systemctl start php7.0-fpm

5. Check it out

$ ps auwx | grep php
root     32061  0.0  0.0 221680 26084 ?        Ss   16:59   0:00 php-fpm: master process (/etc/php/7.0/fpm/php-fpm.conf)
root     32063  0.0  0.0 221680  4992 ?        S    16:59   0:00 php-fpm: pool www
root     32064  0.0  0.0 221680  4992 ?        S    16:59   0:00 php-fpm: pool www