Share an nginx restart script

  • 2020-05-06 12:18:38
  • OfStack

At first, I used
as a direct reboot
killall -9 nginx;/data/nginx/sbin/nginx

If the machine is slow, the kill process cannot be finished in a flash, just execute it again. This is not a particularly safe way to restart. If the configuration is wrong, the restart will fail, and the configuration file will need to be modified before starting again, which will take some time. But for the http community, which is still generally less rigid, that's not a lot of time to lose, as long as it's not done at a critical moment. If you want to use this restart method, I suggest you test it out.

Later I saw an even more fantastic reboot of
on nginx.net
kill -HUP $pid($pid is the process number of the nginx master process)

I usually use
like this
kill -HUP `cat /data/nginx/logs/nginx.pid`

The advantage of this approach is a "smooth restart". As you can see in ps-aux, nginx starts the new process first, the old process still provides the service, and after a certain period of time, the old process service closes automatically, leaving the new process to continue. However, this approach also has disadvantages, if the configuration file is wrong, or resource conflict, the restart is invalid, but nginx does not have any hint! This often makes it difficult to find problems when a changed configuration file does not take effect.

So, finally, I mixed up the problem and got an nginx.sh. This version of nginx.sh still doesn't solve the resource conflict problem of kill-HUP, but it does solve the configuration file problem. Resource conflicts such as port 80 being occupied, log file directory not being created, I'll try again.
 
#!/bin/sh 
BASE_DIR='/data/' 
${BASE_DIR}nginx/sbin/nginx -t -c ${BASE_DIR}nginx/conf/nginx.conf >& ${BASE_DIR}nginx/logs/nginx.start 
info=`cat ${BASE_DIR}nginx/logs/nginx.start` 
if [ `echo $info | grep -c "syntax is ok" ` -eq 1 ]; then 
if [ `ps aux|grep "nginx"|grep -c "master"` == 1 ]; then 
kill -HUP `cat ${BASE_DIR}nginx/logs/nginx.pid` 
echo "ok" 
else 
killall -9 nginx 
sleep 1 
${BASE_DIR}nginx/sbin/nginx 
fi 
else 
echo "######## error: ########" 
cat ${BASE_DIR}nginx/logs/nginx.start 
fi 

Related articles: