supervisor to control Flask-Gunicorn

supervisor is simple and best tool to monitor the processes. In the context of flask it will be of great help to control the gunicorn workers. Say you have 10 worker thread running to service the application.Bringing up and down the workers manually is painful process. You got to execute following command to span 10 worker thread with RTO as 20 secs. To kill them you need to find all the process ids and kill them and it is painful.

gunicorn -w 10-t 20 -b XXXX:8000 app:app

This where supervisor comes in handy. Supervisor has two components

  1. supervisord : It is daemon running on particular port and monitoring all the processes that are spawned through it.Mostly importantly this will service signals from supervisotctrl. It is like beaten down server.
  2. supervisorctrl: this is used to send signals to supervisord to control all the process under its command.

Let us see it in an example how we can configure the same for Flask application:

Install
pip install supervisor

Configuration
echo_supervisord_conf > supervisord.conf

Add configuration relation to process to be controlled to supervisord.conf at the end.

[program:team_ccb]
command = gunicorn -w 8 -t 200 -b XXXXX:8866 app:app
directory = /users/XXXX/penv/prd/ccb_prd_flask/team_ccb
user = mthippar
stdout_logfile=/tmp/XXXXX-app-log
stderr_logfile=/tmp/XXXXX-app-error-log

Kicking off daemon
we need to kick off a daemon to monitor the process.
supervisord -c supervisord.conf

Controlling the application
Now you can start/stop the application with below commands.
supervisorctl start team_ccb
supervisorctl stop team_ccb

Reference :

https://realpython.com/blog/python/kickstarting-flask-on-ubuntu-setup-and-deployment/#part-4--automating

https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-supervisor-on-ubuntu-and-debian-vps

http://supervisord.org/index.html