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
Best Answer
You need make a cron job like root user, so, add new cron job, log as root user, with su and then run
crontab -e
and add it,0 * * * * /etc/init.d/nginx reload
Or edit your
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 with sudo (I think). You need to log on as root or edit crontab as root and add your comand.
Update**************+++
Why don't you run only
Instead of:
Or, better, try this:
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 case we also can use this:
One liner cron than just check if nginx pid is there if not restart it