백엔드 Back-end/장고 Django

Q. 장고에 gunicorn을 같이 써야 하는 이유는?

Tap to restart 2022. 8. 27. 19:00
반응형

A. CPU가 여러개인 환경에서는 훨씬 빠르기 때문이다.

그밖에 HTTPS 적용 등 다양한 기능을 활용할 수 있다.

먼저 이 글 Q. NGINX, gunicorn없이 Django장고만 실행 가능할까? 을 참고해서 gunicorn 없이 테스트를 진행하자.

gunicorn 설치하고 실행하기

아래 명령어를 참고해서 gunicorn을 설치하고 실행하자.

$ pip install gunicorn
$ sudo GUNICORN_CMD_ARGS="--bind=0.0.0.0:80 --workers=3" ./venv/bin/gunicorn config.wsgi:application


설정 설명을 보면 추천 worker수는 CPU core수의 2~4배다.

Worker Processes
workers
Command line: -w INT or --workers INT
Default: 1
The number of worker processes for handling requests.

A positive integer generally in the 2-4 x $(NUM_CORES) range. You’ll want to vary this a bit to find the best for your particular application’s work load.
출처: Worker Processes


Design 문서에서 보면 권장 worker수는 cpu core 2배 + 1이다.

How Many Workers?
DO NOT scale the number of workers to the number of clients you expect to have. Gunicorn should only need 4-12 worker processes to handle hundreds or thousands of requests per second.

Gunicorn relies on the operating system to provide all of the load balancing when handling requests. Generally we recommend (2 x $num_cores) + 1 as the number of workers to start off with. While not overly scientific, the formula is based on the assumption that for a given core, one worker will be reading or writing from the socket while the other worker is processing a request.
출처: How Many Workers?


실제 gunicorn 깃허브 standalone_app.py 예제를 보면 아래처럼 cpu core 2배 + 1로 해놓았다.

def number_of_workers():
    return (multiprocessing.cpu_count() * 2) + 1


ec2의 경우 core가 1개라 worker를 3으로 설정했다.
결과는 아래와 같았다.

ec2 - worker 3개 gunicorn


그냥 장고를 실행한 경우가 아래다.

ec2 - django로 테스트


딱히 더 낫다고 할 수 있는 수준은 아니다.

그래서 내 맥미니로 테스트를 다시 테스트를 했다.

그냥 장고를 실행하고 테스트한 결과다.

장고를 실행해서 맥미니에서 테스트


코어가 6개라 worker 13개로 테스트한 결과다. 유의미하게 빨라진 것을 볼 수 있다.

gunicorn worker 13개로 테스트

설정 문서에 따라 코어수 6개의 3배인 worker 18개로 테스트했을 때 수치도 거의 비슷했다.

반응형