Failed to start nginx.service: Interactive authentication required. with crontab

Dora asked:

I am trying to make a crontab to start nginx if it is stopped.

I googled and found these two scripts


if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
echo "$service is running!!!"
/etc/init.d/$service start

somehow if I run it manually it works fine by doing source scriptName after I add it to crontab even if the service is stopped, it keeps on echoing nginx is running and does not start the service.

Then I found another script in digital ocean


ps auxw | grep nginx | grep -v grep > /dev/null

if [ $? != 0 ]
        /etc/init.d/nginx start > /dev/null

again if I run it manually it works, but it will ask for the user’s password

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to start 'nginx.service'.
Authenticating as: abc,,, (abc)

after I typed in the password ==== AUTHENTICATION COMPLETE ===
will show and starts nginx

then I add the script into crontab…I get this permission error

Failed to start nginx.service: Interactive authentication required.

Does anyone know how I can fix this?

Thanks in advance for any advices.

My answer:

Those scripts you have been trying to use are obsolete and shouldn’t be used on a modern system with systemd.

Try a script like this instead:

if ! systemctl is-active nginx >/dev/null ; then
    systemctl start nginx

But, that is some terribly nasty hackery and probably not necessary, so before you do that, try having systemd restart nginx automatically if it stops. Do that with a systemd drop-in:


which you place as the file /etc/systemd/system/nginx.service.d/override.conf (creating the directory if it doesn’t exist). You can also use systemctl edit nginx to create the file.

And of course, either creating the systemd drop-in, or putting this script in crontab, must be done as root (try using sudo -i for a long running root shell).

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.