This example shows us how to control nginx with supervisor so when nginx goes down for whatever reason, supervisor will bring it up again as a "foreground" process not as a "daemon".


Important


Supervisor uses daemon off; to start Nginx. The daemon off; directive tells Nginx to stay in the foreground. The sudo service nginx stop/start/restart commands won't work. For more information read Stack Overflow answer.


Current nginx process


As you can see below, Nginx is running in "daemon on" mode.


$ ps aux | grep nginx
root 17184 0.0 0.1 124968 1420 ? Ss 16:18 0:00 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;

Setup supervisor


$ sudo nano /etc/supervisor/conf.d/nginx.conf

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
startretries=5
numprocs=1
startsecs=0
process_name=%(program_name)s_%(process_num)02d
stderr_logfile=/var/log/supervisor/%(program_name)s_stderr.log
stderr_logfile_maxbytes=10MB
stdout_logfile=/var/log/supervisor/%(program_name)s_stdout.log
stdout_logfile_maxbytes=10MB

Let supervisor know about new config.


$ sudo supervisorctl reread
nginx: available

Let supervisor start nginx service.


$ sudo supervisorctl update
nginx: added process group

Verify if supervisor started nginx service.


$ sudo supervisorctl
nginx:nginx_00 RUNNING pid 18429, uptime 0:01:47
supervisor>

Check


As you can see below, Nginx is running in "daemon off" mode.


$ ps aux | grep nginx
root 18429 0.0 0.9 124968 9932 ? S 17:20 0:00 nginx: master process /usr/sbin/nginx -g daemon off;

Note


If you want to start/stop a service that is controlled by supervisor, you'll need to use supervisor CLI tool like below.


$ sudo supervisorctl
nginx:nginx_00 RUNNING pid 18429, uptime 0:02:17

supervisor> help
default commands (type help ):
=====================================
add exit open reload restart start tail
avail fg pid remove shutdown status update
clear maintail quit reread signal stop version

supervisor> stop nginx:nginx_00
nginx:nginx_00: stopped

supervisor> start nginx:nginx_00
nginx:nginx_00: started