nginx.service: Can't open PID file /run/nginx

Solution 1:

Just stumbled across your question and thought to leave a short answer:

Systemd does NOT create PID files by itsef. It expects the executables to create it (usually within the /run, or specifically for Ubuntu within the /var/run folder). Systemd only checks, if it has been created after the service started. It also deletes the PID file when killing the service. Reference

Nginx server as forking process does support creating a PID file. To change its location, you may use the pid directive in its nginx.conf file, which you may find in the /etc/nginx folder for the standard package. This pid directive defaults to logs/nginx.pid. Reference

When manually creating the Nginx service, you need to make sure, that both locations within your Systemd nginx.service file and within your Nginx nginx.conf configuration file match.

Solution 2:

Is /run available? Can you cd into /run and touch a file?

cd /run && touch hello.txt && ls -lash

If not that probably means that you want nginx to put the PID file in a location that is not available. You can do 2 things;

  1. Figure out why /run is not available (probably tmpfs configuration)
  2. Put the PID file somewhere else, for example /tmp

Solution 3:

I have an answer in the sense of how to fix this, but I will leave it open for a bit so someone may comment on WHY this is so.

I changed the PID line so the PID file was written to the log folder of the installed nginx folder (/opt/nginx/logs). Anwhere else and it would REFUSE to write the PID file!!!

[Unit]
Description=The NGINX HTTP and reverse proxy server
After=syslog.target network.target remote-fs.target nss-lookup.target

[Service]
Type=forking
PIDFile=/opt/nginx/logs/nginx.pid
ExecStartPre=/opt/nginx/sbin/nginx -t
ExecStart=/opt/nginx/sbin/nginx
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

I have no idea what the reason for this behaviour is and it would be great if some Ubuntu Linux expert could tell me why it wouldn't write the PID anywhere else, including the normal run location /run and /var/run (or even tmp) for example, as is normal in all quoted startup scripts for the program. I think this only happens when it is created from source.