0
0

More than 3 years have passed since last update.

gunicornで起動するworkerに連番を割り振る

Posted at

複数の Worker を起動するアプリケーションにおいて、各 Worker に一意な連番を割り振りたい場面があったのでメモ。

設定ファイルのServer Hooksを使えばワーカーの起動時に呼ばれる処理を定義できるため、ここでワーカープロセス毎に環境変数を設定する。

実装

FastAPI + gunicorn の例

pre_forkイベントを利用する

gunicorn.config.py
import os

workers = 4

def pre_fork(server, worker):
    print('## called pre_fork')
    os.environ['WORKER_ID'] = str(server.worker_age - 1)
main.py
import os
from fastapi import FastAPI

app = FastAPI()

worker_id = os.getenv('WORKER_ID')
print('## WORKER_ID:', worker_id)

@app.get('/')
def index():
    return {'msg': 'hello!'}

起動コマンドと出力

$ gunicorn main:app -c gunicorn.config.py
[2020-11-25 21:07:32 +0900] [18136] [INFO] Starting gunicorn 20.0.4
[2020-11-25 21:07:32 +0900] [18136] [INFO] Listening at: http://127.0.0.1:8000 (18136)
[2020-11-25 21:07:32 +0900] [18136] [INFO] Using worker: sync
## called pre_fork
[2020-11-25 21:07:32 +0900] [18139] [INFO] Booting worker with pid: 18139
## called pre_fork
[2020-11-25 21:07:32 +0900] [18140] [INFO] Booting worker with pid: 18140
## called pre_fork
## WORKER_ID: 0
[2020-11-25 21:07:32 +0900] [18141] [INFO] Booting worker with pid: 18141
## WORKER_ID: 1
## called pre_fork
[2020-11-25 21:07:32 +0900] [18142] [INFO] Booting worker with pid: 18142
## WORKER_ID: 2
## WORKER_ID: 3

pre_forkが4回呼び出され、ワーカー毎に0~3の番号が環境変数にセットされた

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0