Restart nginx without sudo? Restart nginx without sudo? nginx nginx

Restart nginx without sudo?


I just spent a good hour looking at sudoer wildcards and the like trying to solve this exact problem. In truth, all you really need is a root executable script that restarts nginx.

Add this to the /etc/sudoers file

username hostname ALL=NOPASSWD: /path/to/script

Write script as root

#! /bin/bash/bin/kill -HUP `cat /var/run/nginx.pid`

Make the script executable

Test.

sudo /path/to/script


There is a better answer on Stack Overflow that does not involve writing a custom script:

The best practice is to use /etc/sudoers.d/myuser

The /etc/sudoers.d/ folder can contain multiple files that allow users to call stuff using sudo without being root.

The file usually contains a user and a list of commands that the user can run without having to specify a password.

Instructions:

In all commands, replace myuser with the name of your user that you want to use to restart nginx without sudo.

  1. Open sudoers file for your user:

    $ sudo visudo -f /etc/sudoers.d/myuser
  2. Editor will open. There you paste the following line. This will allow that user to run nginx start, restart, and stop:

    myusername ALL=(ALL) NOPASSWD: /usr/sbin/service nginx start,/usr/sbin/service nginx stop,/usr/sbin/service nginx restart
  3. Save by hitting ctrl+o. It will ask where you want to save, simply press enter to confirm the default. Then exit out of the editor with ctrl+x.

Now you can restart (and start and stop) nginx without password. Let's try it.

  1. Open new session (otherwise, you might simply not be asked for your sudo password because it has not timed out):

    $ ssh myusername@myserver
  2. Stop nginx

    $ sudo /usr/sbin/service nginx stop
  3. Confirm that nginx has stopped by checking your website or running ps aux | grep nginx

  4. Start nginx

    $ sudo /usr/sbin/service nginx start
  5. Confirm that nginx has started by checking your website or running ps aux | grep nginx

PS: Make sure to use sudo /usr/sbin/service nginx start|restart|stop, and not sudo service nginx start|restart|stop.


Create a rake task in Rails_App/lib/capistrano/tasks/nginx.rake and paste below code.

namespace :nginx do  %w(start stop restart reload).each do |command|    desc "#{command.capitalize} Nginx"    task command do      on roles(:app) do        execute :sudo, "service nginx #{command}"      end    end  endend

Then ssh to your remote server and open file

  sudo vi /etc/sudoers

and the paste this line (after line %sudo ALL=(ALL:ALL) ALL)

  deploy ALL=(ALL:ALL) NOPASSWD: /usr/sbin/service nginx *

Or, as in your case,

  deploy ALL=(ALL:ALL) NOPASSWD: /etc/init.d/nginx *

Here I am assuming your deployment user is deploy.

You can add here other commands too for which you dont require to enter password. For example

  deploy ALL=(ALL:ALL) NOPASSWD: /usr/sbin/service nginx *, /etc/init.d/mysqld, /etc/init.d/apache2