Search code examples
pythonwebwsgigunicornweb-worker

Gunicorn do not reload worker


Can I tell the Gunicorn to fail when one of the workers failed to boot? I don't want gunicorn to automatically handle and reload the worker for me, but I want it to fail not trying to launch worker again and again. Should I raise any specific exception to master process or some signal? Or I can provide a command line argument when launching master process? I want to implement smth like this logic in worker:

if cond():
    sys.exit(1)

and then all the gunicorn to stop without relaunching this one worker


Solution

  • So, the solution is to use Gunicorn hooks. There are a lot of them but for this particular case you can use worker_int hook. Example of usage might be the following (simplified version, launched with gunicorn app_module:app --config gunicorn_config.py), content of gunicorn_config.py:

    import sys
    
    workers = 1
    loglevel = 'debug'
    
    def worker_int(worker):
        print('Exit because of worker failure')
        sys.exit(1)
    

    And you worker code might be a simple Flask app for example (content of app_module.py:

    from flask import Flask
    
    app = Flask()
    

    Other useful hooks:

    • on_exit - before exiting gunicorn
    • pre_request - before a worker processes the request
    • on_starting - before the master process is initialized

    That's it!