2. Django와 WSGI 서버(Gunicorn) 연동

WSGI(Web Server Gateway Interface)란 웹서버와 python 애플리케이션 간 통신을 가능하게 해주는 규격이다. WSGI server는 WSGI 규격에 맞게 구현된 WAS라고 볼 수 있으며, 웹서버로부터 http request를 받아 WSGI 규격에 맞게 구현된 python 애플리케이션을 호출하고, 그 결과를 다시 http response로 변환하여 웹서버에 전달한다.

Gunicorn은 WSGI server 중 하나로 웹서버로부터 요청을 받아 Django application을 수행하는 역할을 한다. 비슷한 역할을 하는 WSGI server에는 uWSGI, mod_wsgi 등이 있다.


Gunicorn 설치 및 실행하기


Gunicorn은 python 패키지이므로 우선 pip로 install한다.

$ pip install gunicorn

gunicorn 문서에서 worker process갯수는 (2 * $num_cores) + 1로 권장한다. 아래의 명령어를 통해 CPU core 갯수를 확인해보면

$ grep -c processor /proc/cpuinfo
4

core가 4개 있으므로 총 9개의 worker를 생성한다. manage.py가 있는 directory로 이동후 command를 입력한다.

$ cd django_sample
$ gunicorn --bind 0.0.0.0:8000 --workers 9 app.wsgi

Gunicorn을 실행할 때 http 대신 socket을 통해 통신하도록 하려면 bind option을 수정해주면 된다. Gunicorn 실행 후 process를 검색해보면($ ps -ef | grep gunicorn) 9개의 worker와 1개의 master 프로세스가 뜬 것을 확인할 수 있다.

이제 localhost:8000으로 접속하면 Django의 첫화면이 뜨게된다.

Gunicorn 프로세스는 8000번 포트에서 http 요청을 listening하고 있고, 요청이 오면 master process가 적절한 worker process에게 요청을 할당한다. 요청을 전달받은 worker process는 Django의 wsgi.py 파일을 찾아 Django application을 호출하여 로직을 수행한다.


_config.yml


Gunicorn을 service로 등록하기


Gunicorn을 service로 등록해서 재부팅시에도 자동으로 실행되도록 설정해보자. 우선 gunicorn service file을 생성($ vim /etc/systemd/system/gunicorn.service)한 뒤 아래의 내용을 채워넣는다. 직접 수정해야하는 부분은 User, WorkingDirectory, ExecStart 항목이다.

  • ${사용자 이름}: $ whoami
  • ${Django project path}: manage.py가 있는 directory의 path
  • ${Gunicorn binary path}: $ whereis gunicorn
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=${사용자 이름}
Group=www-data
WorkingDirectory=${Django project path}
ExecStart=${gunicorn binary path} --workers 9 --bind 0.0.0.0:8000 app.wsgi:application --timeout 600

[Install]
WantedBy=multi-user.target

timeout이 짧으면(default: 30s) 용량이 큰 파일을 업로드하는 등의 동작을 하다가 Connection이 끊기기 때문에 충분히 늘려준다.

service 파일을 작성했으면 아래의 명령어를 이용해 service를 시작하면 된다.

$ sudo systemctl start gunicorn
$ sudo systemctl enable gunicorn

service가 제대로 시작했는지 $ systemctl status gunicorn 로 확인해본다. 이제 재부팅을 해도 gunicorn process가 자동으로 뜨게 된다.