[Django Install] 9. Nginx + uwsgi + Django 연결

[순서]

전체 구조
파이썬 가상화 설치
Django 설치
Django static 파일 마이그레이션
uwsgi 설치
uwsgi 서비스 등록
Nginx 설치
Nginx - Django 연동
실행순서


[전체 구조]

web browser  <=>  web server (nginx) <=> unix socket <=> uwsgi <=> django


[파이썬 가상화 설치]

파이썬은 이미 설치된 것으로 가정하고 진행.
파이썬 가상화 환경도 설치된 것으로 가정하고 진행.

파이썬 가상화명 : prefity
파이썬 가상화 홈디렉토리 : /home/ubuntu/.virtualenvs/prefity


[Django 설치]

Django는 이미 설치된 것으로 가정하고 진행.

프로젝트명 : prefity
프로젝트 디렉토리 : /home/ubuntu/prefity
settings.py 수정
  - debug를 False로 한다.
  - import os 추가
  - ALLOWED_HOST = '*' 변경


[Django static 파일 마이그레이션]

settings.py 수정

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'staticfiles'),
)
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')


STATIC_ROOT = os.path.join(BASE_DIR, "static") 에 설정된 static 디렉토리 하위에 app별 폴더가 
만들어진다. (app의 static 폴더의 images, js, css 파일에 변경이 있으면 실행이 필요하다)
MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') 에 설정된 디렉토리에는 첨부파일이나
업로드 이미지 파일이 만들어진다.
(위 명령어와 관련이 없으며, 관리자나 사용자가 업로드한 파일들이 저장된다.)

설정과 관련된 디렉토리 생성

cd /home/ubuntu/prefity
mkdir static
mkdir staticfiles
mkdir media

Nginx에서 사용할 static 파일을 생성한다 (static 파일 변경 시 마다 실행)

python manage.py collectstatic # static_root, media_root만 영향을 준다.


[uwsgi 설치]

파이썬 가상화 환경에 로그인한 후 실행

pip install uwsgi

오류 발생 시 확인 사항
sudo yum search python3 | grep devel # 파이썬 개발환경 설치 여부 확인
sudo yum install python3-devel.x86_64 # install

mkdir /home/ubuntu/prefity/uwsgi # uwsgi 디렉토리 생성
vi /home/ubuntu/prefity/uwsgi/uwsgi.ini # 파일생성 (아래 내용으로 생성)

# mysite_uwsgi.ini file
[uwsgi]

# Django-related settings
# the base directory (full path)
chdir           = /home/ubuntu/prefity
# Django's wsgi file
module          = prefity.wsgi
# the virtualenv (full path)
home            = /home/ubuntu/.virtualenvs/prefity

# process-related settings
# master
master          = true
# maximum number of worker processes
processes       = 3
# the socket (use the full path to be safe
socket          = /home/ubuntu/prefity/uwsgi/prefity.sock
# ... with appropriate permissions - may be needed
chmod-socket    = 666
uid = ec2-user # 현재 사용자
gid = ec2-user # 현재 사용자
# log file 설정
logto = /home/ubuntu/prefity/uwsgi/uwsgi.log
logfile-chown = ec2-user:ec2-user
logfile-chmod = 640
# clear environment on exit
vacuum          = true
touch-reload = /home/ubuntu/prefity/prefity/settings.py #  설정 변경 시 자동로드
py-autoreload = 1  # 소스코드 변경 시 자동로드


[uwsgi 서비스 등록]
sudo vi /etc/systemd/system/uwsgi.service
[Unit]
Description=uWSGI
After=syslog.target

[Service]
ExecStart=/home/ubuntu/.virtualenvs/prefity/bin/uwsgi --ini /home/ubuntu/prefity/uwsgi/uwsgi.ini
# Requires systemd version 211 or newer
RuntimeDirectory=uwsgi
Restart=always
KillSignal=SIGQUIT
Type=notify
StandardError=syslog
NotifyAccess=all

[Install]
WantedBy=multi-user.target

sudo systemctl enable uwsgi # 심볼릭 링크 생성
sudo systemctl start uwsgi# uwsgi실행

sudo systemctl daemon-reload # /etc/systemd/system/uwsgi.service 변경 시 실행


[Nginx 설치]

sudo apt-get install nginx # ubuntu
sudo yum install nginx # redhat, centos
sudo amazon-linux-extras install -y nginx1 # amazon linux 2


설치 후 자동적으로 Nginx가 Start 된다.

프로세스 시작 : sudo service nginx start
프로세스 종료 : sudo service nginx stop
프로세스 재시작 : sudo service nginx restart
프로세스 상태 : sudo service nginx status

[Nginx - Django 연동]

/etc/nginx/nginx.conf 파일수정 (아래 내용으로 수정)

# sock 파일을 접근하려면 nginx가 root 권한이 필요함
user root; 

# the upstream component nginx needs to connect to
upstream django {
    server unix:///home/ubuntu/prefity/uwsgi/prefity.sock;
}

# Default server configuration
#
server {
        listen 8080 default_server;
        listen [::]:8080 default_server;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name prefity.com;
        # char  utf-8;

        # Django static
        location /static {
                alias /home/ubuntu/prefity/static;
        }

        # Django media
        location /media  {
                alias /home/ubuntu/prefity/media;
        }

        # Finally, send all non-media requests to the Django server.
        location / {
                uwsgi_pass  django;
                include     /home/ubuntu/prefity/uwsgi/uwsgi_params;
        }
}

uwsgi_params 파일 복사
cp /etc/nginx/uwsgi_params /home/ubuntu/prefity/uwsgi_params


[실행순서]

sudo systemctl start uwsgi 
sudo systemctl start nginx


[uwsgi 실행 시 sqlite3 버전 오류 시 조치사항]

sudo systemctl start uwsgi 실행 시 log에 아래와 같은 오류가 나올 수 있다.

'SQLite 3.9.0 or later is required (found %s).' % Database.sqlite_version
django.core.exceptions.ImproperlyConfigured: SQLite 3.9.0 or later is required (found 3.7.17).
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 13903)
spawned uWSGI worker 1 (pid: 13904, cores: 1)
Python auto-reloader enabled

아래완 같이 조치한다.

rm /usr/lib64/libsqlite3.so.0
ln -s /usr/lib64/libsqlite3.so.0.8.6 /usr/lib64/libsqlite3.so.0

댓글

이 블로그의 인기 게시물

[Django Install] 9.1 sc제일은행 nginx-django 연결

[Django APP] django-widget-tweaks

[Django App] django-user-agents