Failed to Stop or Restart Nginx Server Through Serevice Command

Many people are accustomed to start a Nginx web server through init scripts and then they can control the state of the server through service command, such as sudo service nginx restart. But sometimes unobvious config error makes the scripts failed to work. Here I will show an error related to pid directive in the config file of nginx, which defaultly located at /opt/nginx/conf/nginx.conf.
As ignored by many people, some init scripts assump there is a pid file of nginx located at /var/run/nginx.pid, but in the fact, the default pid file for nginx is /opt/nginx/logs/nginx.pid. Because the scripts can’t get the correct pid or even get nothing, they failed to stop the nginx process, some tasks dependent on it will be failed too, for example, you are not able to restart the server.

To resolve this problem, you need to:

  1. Force terminating your server through:
1
$ sudo service nginx destroy
  1. Open your nginx config file to edit:
1
$ sudo vim /opt/nginx/conf/nginx.conf
  1. Specify the path of your pid file:
1
2
# /opt/nginx/conf/nginx.conf
pid /var/run/nginx.pid
  1. After saving your change, start your server now:
1
$ sudo service nginx start
  1. To confirm that your pid config has taken effect, you can cat your pid file and/or try to restart your server through service command:
1
2
$ cat /var/run/nginx.pid
$ sudo service nginx restart

As expected, you will see the screen out “OK” for your operations.

Comments