问题
I am trying to restart the NGINX service from a script which is called via a cron job (it works when run in the command line by the root user) - I am not sure if this is relevant but the cron job in question is also created via a script. I have tried multiple commands but the current one that I am using is the below:
sudo /etc/init.d/nginx restart
Any help on this would be great!
UPDATE
Below is the script that the cron runs and tries to reload the nginx service
#!/bin/bash
NGINX_CONFIG='/etc/nginx/sites-available'
NGINX_SITES_ENABLED='/etc/nginx/sites-enabled'
WEB_DIR='/var/www/vhosts/demos'
EMAIL=$1
DOMAIN=$2
SITE_DIR=$3
echo $DOMAIN
echo $SITE_DIR
# Remove the nginx configurtations
rm -Rf $NGINX_CONFIG/$DOMAIN.conf
rm -Rf $NGINX_SITES_ENABLED/$DOMAIN.conf
# Remove the access log
rm -Rf /var/log/nginx/$SITE_DIR.access.log
# Remove unicorn socket log
rm -Rf /tmp/unicorn.$SITE_DIR.sock
# Remove the DB
sudo psql -U postgres -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '_$SITE_DIR' AND pid <> pg_backend_pid();"
dropdb -U postgres $SITE_DIR
# Remove the sites application from the server
rm -Rf $WEB_DIR/$SITE_DIR/
if [[ ! "$(/sbin/service nginx status)" =~ "start/running" ]]
then
/etc/init.d/nginx reload
fi
回答1:
You need make a cron job like root user, so, add new cron job, log as root user, whit su and then run crontab -e and add it,
0 * * * * /etc/init.d/nginx reload
Or edit your
/etc/crontab
with your root user and add the cron
0 * * * * root /etc/init.d/nginx reload
(adjust the schedule as needed; the above will run every hour on the hour)
You cant run a cron whit sudo ( I think ) you need log as root or edit crontab as root and add your comand.
Update**************+++
Why dont run only
/etc/init.d/nginx reload
Instead of:
if [[ ! "$(/sbin/service nginx status)" =~ "start/running" ]] then /etc/init.d/nginx reload fi
Or better try this:
/etc/init.d/nginx status > /dev/null
status="$?"
if [ $status -eq "0" ]; then
/etc/init.d/nginx reload
fi
There you can add a else if nginx is stoped to restart it or something like that... forme working I use it on my lite monitoring script http://kb.skamasle.com/2013/monitorear-servicios-ftp-mysql-apache-etc-y-levantar-si-esta-caido/
In any way we also can use this:
* * * * * /usr/bin/pgrep nginx > /dev/null || /etc/init.d/nginx restart >> /var/log/messages
One liner cron than just check if nginx pid is there if not restart it
来源:https://stackoverflow.com/questions/25953339/how-to-get-nginx-to-restart-reload-from-a-cron-job