Gunicorn do not reload worker
Asked Answered
F

2

6

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

Faultfinding answered 24/5, 2016 at 11:24 Comment(0)
F
4

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!

Faultfinding answered 25/5, 2016 at 9:8 Comment(0)
B
1

Unfortunately, the accepted answer does not work, at least not in 2024 with Gunicorn 22.0.0.

As explained in this answer and this one also, you don't need to implement a Gunicorn hook, you just need to change your app's exit code to errno.EINTR (4):

import errno
import sys

...

if cond():
    sys.exit(errno.EINTR)
Bulge answered 28/6, 2024 at 19:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.