Failed to stop or restart Nginx server through serevice command

09/Aug/2013 · 2 minute read

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/, but in the fact, the default pid file for nginx is /opt/nginx/logs/ 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:
$ sudo service nginx destroy
  1. Open your nginx config file to edit:
$ sudo vim /opt/nginx/conf/nginx.conf
  1. Specify the path of your pid file:
# /opt/nginx/conf/nginx.conf
pid /var/run/
  1. After saving your change, start your server now:
$ 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:
$ cat /var/run/
$ sudo service nginx restart

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