Nginx Gunicorn Django Mysql 연동

2023. 12. 3. 08:05project

참고 사이트

 

https://docs.gunicorn.org/en/latest/index.html

 

Gunicorn - WSGI server — Gunicorn 21.2.0 documentation

 

docs.gunicorn.org

 

 

[SSL] + 3tier 실습(Nginx-Re.. : 네이버블로그 (naver.com)

 

[SSL] + 3tier 실습(Nginx-React, Gunicorn-Django, MySQL)

3계층을 클라우드에 구현하는 실습. 웹 서버 Nginx 클라이언트 접속 React 프로젝트 백엔드를 요청(gunic...

blog.naver.com

 

 

[Django] - Static file Nginx로 처리 (velog.io)

 

[Django] - Static file Nginx로 처리

이전에 Nginx 정리하면서 해보지는 않았지만 간단히 포스팅 한 적 있는데 오늘 따라해보니깐 완전 산전수전~낼 회사가야 되는데 분노의 새벽 3시에 글써버리기HTTP 프로토콜을 이용해 정적 파일을

velog.io

 

 

WAS에서 설정
  • django와 DB 연동

# django server에서 mysqlclient 설치 시 아래와 같이 명령

apt install default-libmysqlclient-dev pkg-config -y
pip install mysqlclient

 

 

# settings.py 파일 수정

 78 DATABASES = {
 79     'default': {
 80         'ENGINE': 'django.db.backends.mysql',
 81         'NAME': 'web',
 82     'USER': 'admin',
 83     'PASSWORD': 'admin',
 84     'HOST': '10.0.2.236',
 85     'PORT': '3306',
 86     'OPTIONS': {
 87         'init_command': 'SET sql_mode="STRICT_TRANS_TABLES"'
 88     }
 89     }
 90 }

 

 

  • Gunicorn 설치
pip3 install gunicorn

 

# gunicorn 도움말

gunicorn -h

 

 

  • 정적 파일 처리를 위해 settings.py 파일 수정
from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = os.path.dirname(BASE_DIR)


# Static files
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')


# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

 

# BASE_DIR에서 아래 명령어 실행

python manage.py colletstatic

 

 

  • Gunicorn 실행
[manage.py가 있는 작업 디렉토리]$ gunicorn -b 0:8000 'aws.wsgi:application'

 

 

  • 설정 파일을 이용하여 gunicorn 실행

# File name : gunicorn.py

bind = '0.0.0.0:8000'
workers = 2
errorlog = './gunicorn_log/errorlog.txt'
accesslog = './gunicorn_log/accesslog.txt'

 

# 로그 파일 저장을 위한 디렉토리 생성

mkdir gunicorn_log

 

# gunicorn 실행

gunicorn --config gunicorn.py 'aws.wsgi:application'

 

 

WS에서 설정

 

$ sudo vi /etc/nginx/sites-available/proj.server

server {
    listen 80;
    server_name localhost;

    access_log /var/log/nginx/proj.access.log;
    error_log /var/log/nginx/proj.error.log;

    location /static/ {
        alias /project/static/;
    }

    location /media/ {
        alias /project/media/;
    }

    location / {
        include proxy_params;
        proxy_pass http://[NLB DNS name]:8000;
    }
}

 

 

  • soft link 연결

sudo rm /etc/nginx/sites-enabled/default

sudo ln -s /etc/nginx/sites-available/proj.server /etc/nginx/sites-enabled/default

 

 

  • nginx 재시작

sudo nginx -t

sudo systemctl restart nginx

 

# 웹 브라우저를 통해 정상 접속 확인

접속 성공!

 

 

gunicorn 데몬 등록

 

# virtualenv 설치

apt install python3-virtualenv

 

# 가상환경 생성

virtualenv venv

 

# managy.py 위치한 디렉토리에서 아래 명령을 통해 가상환경 진입

source venv/bin/activate
cf) 가상환경에서 나갈 시 'deactivate'

 

# django, gunicorn, mysqlclient 설치

pip3 install django
pip3 install gunicorn
sudo apt install default-libmysqlclient-dev pkg-config -y
pip install mysqlclient

 

# /etc/systemd/system/gunicorn.service 생성

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
WorkingDirectory=/project/
ExecStart=/project/venv/bin/gunicorn --config gunicorn.py 'aws.wsgi:application'

[Install]
WantedBy=multi-user.target

 

# gunicorn 데몬으로 실행

sudo systemctl daemon-reload
sudo systemctl start gunicorn
sudo systemctl satatus gunicorn
cf) 상태 확인 시 enable이 되어 있어서 굳이 명령어를 넣지 않았다.

 

이 포스팅에서는 데몬등록 시 가상환경을 만들었지만 처음부터 가상환경을 만들고 시작하면 패키지 충돌 없이 django를 더 잘 운영할 수 있을 것이다.

'project' 카테고리의 다른 글

Elasticache Redis  (1) 2023.12.06
오토 스케일링  (2) 2023.12.05
WAF  (0) 2023.11.25
S3 lifecycle  (0) 2023.11.23
HTTPS  (0) 2023.11.23