Hooks are configurable rules that gets triggered on the occurrence of a specific event.

Gunicorn comes with a set of hooks. With these hooks, we will be able to monitor and track the events or changes happening in the system. Some of the possible events are

  • Starting of a worker
  • Restart event of gunicorn server
  • Worker exit
  • Worker restart
  • Adding new workers

The details are available in the Gunicorn website.

Hooks can be configured very easy.

  • We just need to define the hooks in that way we want.
  • Pass the configuration file to the gunicorn config file and start the gunicorn server

A Sample gunicorn hook file is given below. Here I have configured few hooks and printing the details. We can keep any logic within the hook definition.

def on_starting(server):
Do something on server start
print("Server has started")
def on_reload(server):
Do something on reload
print("Server has reloaded")
def post_worker_init(worker):
Do something on worker initialization
print("Worker has been initialized. Worker Process id –>", worker.pid)

Lets create a simple python flask application to perform this test. The sample code is given below.

from flask import Flask

app = Flask(__name__)

def hello():
    return "Hello World!"

if __name__ == '__main__':

Now lets run the application using gunicorn.

gunicorn -c gunicorn_hooks_config.py app:app

This will load the hooks and each of those gets triggered based on the occurrence of the event. This is the best way to track the events happening in gunicorn.