Ossian Story
article thumbnail


[WEB & WAS] Django & Nginx & uWSGI - Python Virtualenv


Python 3.x 설치 및 Virtualenv 환경 구성


아래 포스팅을 참조하여 Python 3.x Virtualenv 환경 구성하기


[Python] Python 3.x Virtualenv(가상환경) 만들기




Django 2.1 설치


Django 2.2 버전 설치 시 sqlite 버전 이슈로 정상적인 구동이 안될 수 있으므로 Django 2.1버전을 설치합니다.

기본적으로 제공되는 sqlite 이외에 MariaDB 또는 MySQL 등을 설치할 경우에는 상관 없습니다.


Python Virtualenv 실행 상태에서 Django 설치


(env_django) [root@djang-dev ~]# pip install django==2.1
 
Collecting django==2.1
  Downloading https://files.pythonhosted.org/packages/51/1a/e0ac7886c7123a03814178d7517dc822af0fe51a72e1a6bff26153103322/Django-2.1-py3-none-any.whl (7.3MB)
    100|################################| 7.3MB 962kB/s
Collecting pytz (from django==2.1)
  Downloading https://files.pythonhosted.org/packages/3d/73/fe30c2daaaa0713420d0382b16fbb761409f532c56bdcc514bf7b6262bb6/pytz-2019.1-py2.py3-none-any.whl (510kB)
    100|################################| 512kB 994kB/s
Installing collected packages: pytz, django
Successfully installed django-2.1 pytz-2019.1




Django Project 생성


프로젝트 생성위치는 원하시는 디렉토리에 생성하면 됩니다.


/opt
(env_django) [root@djang-dev opt]# django-admin startproject django_project
 
(env_django) [root@djang-dev opt]# ls
django_project




Django 구동 확인


setting.py의 ALLOWED_HOSTS 값 변경


(env_django) [root@djang-dev opt]# vi django_project/django_project/settings.py
 
 
# ALLOWED_HOSTS 
--------------------------------------------------------------------------------
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
 
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '7xbs1kj&@h*l2!$eaapt3tynsa6y=un#s0^)3bghw6j1ylwpjd'
 
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
 
ALLOWED_HOSTS = ['*']
 
--------------------------------------------------------------------------------




Django 실행 후 작동 확인


(env_django) [root@djang-dev django_project]# pwd
/opt/django_project
 
(env_django) [root@djang-dev django_project]# ls -al
total 4
drwxr-xr-x  3 root root  45 Apr 24 00:59 .
drwxr-xr-x. 3 root root  28 Apr 24 00:59 ..
drwxr-xr-x  2 root root  74 Apr 24 01:03 django_project
-rwxr-xr-x  1 root root 546 Apr 24 00:59 manage.py
 
 
(env_django) [root@djang-dev django_project]# ./manage.py runserver 0.0.0.0:80
 
 
-------------------------------------------------------------------------------------------------------------------------------------------------------
Performing system checks...
 
System check identified no issues (0 silenced).
 
You have 15 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
 
April 232019 - 16:04:13
Django version 2.1, using settings 'django_project.settings'
Starting development server at http://0.0.0.0:80/
Quit the server with CONTROL-C.
 
-------------------------------------------------------------------------------------------------------------------------------------------------------




Web Browser에서 Django가 실행중인 서버로 접속하여 정상 구동 확인





uWSGI 설치


Yum을 통해 gcc 설치


(env_django) [root@djang-dev django_project]# yum install -y gcc
 
---------------------------------------------------------------------
Failed to set locale, defaulting to C
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.neowiz.com
 * epel: www.ftp.ne.jp
 * extras: mirror.kakao.com
 * ius: mirrors.kernel.org
 * updates: mirror.kakao.com
Resolving Dependencies
 
..........
 
Complete!
(env_django) [root@djang-dev django_project]#
 
---------------------------------------------------------------------




PIP를 통해 uWSGI 설치


(env_django) [root@djang-dev django_project]# pip install uwsgi
 
--------------------------------------------------------------------------------------------------------------------------------------------------------
Collecting uwsgi
  Downloading https://files.pythonhosted.org/packages/e7/1e/3dcca007f974fe4eb369bf1b8629d5e342bb3055e2001b2e5340aaefae7a/uwsgi-2.0.18.tar.gz (801kB)
    97|############################### | 778kB 763kB/s eta 0:00:01
 
.............
 
Successfully built uwsgi
Installing collected packages: uwsgi
Successfully installed uwsgi-2.0.18
--------------------------------------------------------------------------------------------------------------------------------------------------------




uWSGI 환경설정


uWSGI 디렉토리 및 Config 파일 생성


* uWSGi Config 디렉토리 생성
(env_django) [root@djang-dev django_project]# mkdir -p /etc/uwsgi/sites
 
* uWSGI 로그 디렉토리 생성
(env_django) [root@djang-dev django_project]# mkdir -p /var/log/uwsgi
 
* uWSGI Config 파일 생성
(env_django) [root@djang-dev django_project]# vi /etc/uwsgi/sites/django.ini
 
-----------------------------------------------------------------------------
[uwsgi]
project = django_project                               # 프로젝트 이름
username = root                                        # 사용자
base = /opt/django_project                             # 프로젝트 경로
 
### Django Settings
# base directory
chdir = /opt/django_project                            # 프로젝트 경로
 
# python path
home = /root/.virtualenvs/env_django                   # Python Virtualenv 경로
 
# virtualenv path
virtualenv = /root/.virtualenvs/env_django             # Python Virtualenv 경로
 
# wsgi.py path
module = django_project.wsgi:application               # 프로젝트 이름.wsgi:application
 
master = true
processes = 5
 
uid = root
socket = /run/uwsgi/django.sock                        # 소켓 이름
chown-socket = root:nginx
chmod-socket = 666
vacuum = true
 
logto = /var/log/uwsgi/django.log                      # 로그 경로
-----------------------------------------------------------------------------




Django Project 폴더에서 uwsgi 명령어 실행 및 브라우저에서 Django 정상구동 확인


(env_django) [root@djang-dev django_project]# pwd
/opt/django_project
 
(env_django) [root@djang-dev django_project]# uwsgi --http :80 --module django_project.wsgi





Nginx 설치


Yum을 사용하여 nginx 설치


(env_django) [root@djang-dev django_project]# yum install -y nginx
 
-----------------------------------------------------------------------------
Failed to set locale, defaulting to C
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
 * base: ftp.neowiz.com
 * epel: www.ftp.ne.jp
 * extras: mirror.kakao.com
 
........
 
Complete!
-----------------------------------------------------------------------------




Nginx 환경설정


Django 사이트용 Nginx Config 파일 생성 및 설정


(env_django) [root@djang-dev django_project]# vi /etc/nginx/conf.d/django.conf
 
--------------------------------------------------------------------------------
server{
        listen 80;
        server_name 192.168.126.251;
 
        location / {
                include uwsgi_params;
                uwsgi_pass unix:/run/uwsgi/django.sock;
        }
 
        location /static/ {
             alias /opt/django_project/.static_root/;
        }
 
}
--------------------------------------------------------------------------------




nginx.conf 파일에서 기본 80 포트 설정 주석처리, Django 사이트를 80 포트가 아닌 다른 포트를 사용할 경우 주석처리 하지 않아도 됨


(env_django) [root@djang-dev django_project]# vi /etc/nginx/nginx.conf
 
--------------------------------------------------------------------------
#    server {
#        listen       80 default_server;
#        listen       [::]:80 default_server;
#        server_name  _;
#        root         /usr/share/nginx/html;
#
#        # Load configuration files for the default server block.
#        include /etc/nginx/default.d/*.conf;
#
#        location / {
#        }
#
#        error_page 404 /404.html;
#            location = /40x.html {
#        }
#
#        error_page 500 502 503 504 /50x.html;
#            location = /50x.html {
#        }
#    }
--------------------------------------------------------------------------
cs



Django Static File 설정


Django settings.py 파일 맨 하단부분에 Static File 정의


(env_django) [root@djang-dev django_project]# vi settings.py
 
-------------------------------------------------------------
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
 
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = [
    STATIC_DIR,
]
STATIC_ROOT = os.path.join(BASE_DIR, '.static_root')
-------------------------------------------------------------



settings.py 설정 후 Static 디렉토리 생성 및 Static 파일 모으기

* Static 디렉토리 생성
(env_django) [root@djang-dev django_project]# mkdir static
(env_django) [root@djang-dev django_project]# mkdir .static_root
 
* Static 파일 모으기
(env_django) [root@djang-dev django_project]# ./manage.py collectstatic
 
119 static files copied to '/opt/django_project/.static_root'.






uWSGI 서비스 데몬 등록


uWSGI 데몬 서비스 생성


(env_django) [root@djang-dev ~]# vi /etc/systemd/system/uwsgi.service
 
----------------------------------------------------------------------
[Unit]
Description=uWSGI service
 
[Service]
 
ExecStartPre=/bin/mkdir -/run/uwsgi
 
ExecStartPre=/bin/chown root:nginx /run/uwsgi
 
ExecStart=/root/.virtualenvs/env_django/bin/uwsgi --emperor /etc/uwsgi/sites
Restart=always
Type=notify
NotifyAccess=all
 
[Install]
WantedBy=multi-user.target
----------------------------------------------------------------------
 
(env_django) [root@djang-dev ~]# systemctl daemon-reload




uWSGI 서비스 구동 확인



(env_django) [root@djang-dev django_project]# systemctl start nginx
(env_django) [root@djang-dev django_project]# systemctl start uwsgi




브라우저에서 Django 정상구동 확인




uwsgi 로그 확인


(env_django) [root@djang-dev django_project]# tail -f /var/log/uwsgi/django.log
 
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI master process (pid: 10546)
spawned uWSGI worker 1 (pid: 10548, cores: 1)
spawned uWSGI worker 2 (pid: 10549, cores: 1)
spawned uWSGI worker 3 (pid: 10550, cores: 1)
spawned uWSGI worker 4 (pid: 10551, cores: 1)
spawned uWSGI worker 5 (pid: 10552, cores: 1)
[pid: 10551|app: 0|req: 1/1192.168.126.1 () {42 vars in 701 bytes} [Tue Apr 23 17:29:16 2019] GET / => generated 16348 bytes in 13 msecs (HTTP/1.1 2003 headers in 96 bytes (1 switches on core 0)
announcing my loyalty to the Emperor...
[pid: 10552|app: 0|req: 1/2192.168.126.1 () {42 vars in 701 bytes} [Tue Apr 23 17:30:43 2019] GET / => generated 16348 bytes in 12 msecs (HTTP/1.1 2003 headers in 96 bytes (1 switches on core 0)
announcing my loyalty to the Empero
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------







profile

Ossian Story

@ossians