웹사이트 검색

CentOS 8에 Django Python Framework를 설치하는 방법


이 페이지에서

  1. 전제 조건
  2. 필수 패키지 설치\n
  3. 장고 설치
  4. Django 프로젝트 만들기\n
  5. Django 애플리케이션 시작\n
  6. SELinux 및 방화벽 구성\n
  7. Django 애플리케이션 액세스\n
  8. Nginx 및 Gunicorn 설치
  9. Django용 Systemd 서비스 파일 만들기
  10. Django용 Nginx 구성
  11. 결론

Django는 Python 웹 애플리케이션 개발에 사용되는 무료 오픈 소스 및 고급 웹 프레임워크입니다. 안전하고 확장 가능한 웹 애플리케이션을 구축하는 데 도움이 되는 일련의 도구가 함께 제공됩니다. 주요 목표는 복잡한 애플리케이션의 생성을 용이하게 하고 내부 구조를 관리하는 것입니다.

이 튜토리얼에서는 CentOS 8에서 Django를 설치하고 Nginx를 Django의 리버스 프록시로 구성하는 방법을 배웁니다.

전제 조건

  • CentOS 8을 실행하는 서버.\n
  • 서버에 루트 암호가 구성되어 있습니다.\n

필수 패키지 설치

Django는 Python 기반 프레임워크이므로 시스템에 Python 및 PIP를 설치해야 합니다. 다음 명령을 실행하여 설치할 수 있습니다.

dnf install python36 python3-pip -y

두 패키지가 모두 설치되면 다음 단계로 진행할 수 있습니다.

장고 설치

아래와 같이 PIP 명령으로 Django를 설치할 수 있습니다.

pip3 install Django

Django를 설치한 후 다음 명령을 사용하여 Django의 버전을 확인할 수 있습니다.

django-admin --version

다음 출력에서 Django 버전을 볼 수 있습니다.

3.0.3

장고 프로젝트 만들기

이 시점에서 Django가 설치됩니다. 이제 새로운 Django 애플리케이션을 만들 차례입니다.

아래와 같이 /opt 디렉터리 내에서 django-admin 명령을 사용하여 새 Django 애플리케이션을 만들 수 있습니다.

cd /opt
django-admin startproject djangoproject

django 프로젝트가 생성되면 디렉토리를 djangoproject로 변경하고 다음 명령을 사용하여 변경 사항을 마이그레이션합니다.

cd djangoproject
python3 manage.py migrate

다음과 같은 결과가 표시되어야 합니다.

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying sessions.0001_initial... OK

다음으로 Django 프로젝트를 관리하기 위한 관리자 사용자 계정을 생성해야 합니다. 다음 명령으로 만들 수 있습니다.

python3 manage.py createsuperuser

사용자 이름, 이메일 및 비밀번호를 제공하라는 메시지가 표시됩니다. 아래와 같이 선택에 따라 제공할 수 있습니다.

Username (leave blank to use 'root'): dadmin
Email address: 
Password: 
Password (again): 
Superuser created successfully.

완료되면 다음 단계로 진행할 수 있습니다.

장고 애플리케이션 시작

기본적으로 Django 애플리케이션은 원격 호스트에서 액세스할 수 없습니다. 따라서 외부 호스트에 대해 Django를 허용해야 합니다. settings.py에 서버 IP를 추가하면 됩니다.

nano /opt/djangoproject/djangoproject/settings.py

다음 줄을 변경합니다.

ALLOWED_HOSTS = ['your-server-ip']

파일을 저장하고 닫습니다. 그런 다음 다음 명령을 사용하여 Django 애플리케이션을 시작합니다.

cd /opt/djangoproject
python3 manage.py runserver 0.0.0.0:8000

다음 출력이 표시되어야 합니다.

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
March 03, 2020 - 02:31:19
Django version 3.0.3, using settings 'djangoproject.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

Django application is now started and runs on port 8000. 

이제 Django 애플리케이션이 시작되고 포트 8000에서 실행됩니다. 이제 다음 단계를 진행할 수 있습니다.

SELinux 및 방화벽 구성

다음으로 방화벽을 통해 포트 8000 및 80을 허용해야 합니다. 다음 명령으로 허용할 수 있습니다.

firewall-cmd --permanent --add-port=8000/tcp
firewall-cmd --permanent --add-port=80/tcp
firewall-cmd --reload

그런 다음 다음 명령을 사용하여 SELinux를 구성합니다.

setsebool httpd_can_network_connect on -P

완료되면 다음 단계로 진행할 수 있습니다.

Django 애플리케이션에 액세스

URL http://your-server-ip:8000을 방문하여 Django 애플리케이션에 액세스할 수 있습니다. 다음 페이지가 표시됩니다.

URL http://your-server-ip:8000/admin을 사용하여 Django 관리 인터페이스에 액세스할 수도 있습니다. 다음 페이지가 표시됩니다.

관리자 사용자 이름, 암호를 제공하고 로그인 버튼을 클릭합니다. 다음 페이지가 표시됩니다.

Nginx 및 Gunicorn 설치

이 섹션에서는 Django 서비스를 생성하고 관리하기 위해 Gunicorn을 설치하고 Django 응용 프로그램을 제공하기 위해 Nginx를 설치합니다.

먼저 다음 명령으로 Nginx를 설치합니다.

dnf install nginx -y

다음으로 아래와 같이 PIP 명령을 사용하여 Gunicorn을 설치합니다.

pip3 install gunicorn

두 패키지가 모두 설치되면 Nginx 서비스를 시작하고 다음 명령을 사용하여 시스템 재부팅 후 시작되도록 활성화합니다.

systemctl start nginx
systemctl enable nginx

다음으로 아래와 같이 /opt/djangoproject 디렉토리의 소유권을 Nginx로 변경합니다.

chown -R nginx:nginx /opt/djangoproject

Django용 Systemd 서비스 파일 생성

다음으로 다음 명령을 사용하여 Django 서비스를 관리하기 위한 systemd 서비스 파일을 생성합니다.

nano /etc/systemd/system/django.service

다음 줄을 추가합니다.

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

[Service]
User=nginx
Group=nginx
WorkingDirectory=/opt/djangoproject
ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:application

[Install]
WantedBy=multi-user.target

파일을 저장하고 닫은 후 다음 명령을 사용하여 systemd 데몬을 다시 로드합니다.

systemctl daemon-reload

그런 다음 Django 서비스를 시작하고 다음 명령을 사용하여 시스템 재부팅 후 시작되도록 활성화합니다.

systemctl start django
systemctl enable django

이제 다음 명령을 사용하여 Django 서비스의 상태를 확인할 수 있습니다.

systemctl status django

다음 출력이 표시되어야 합니다.

? django.service - django daemon
   Loaded: loaded (/etc/systemd/system/django.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2020-03-02 22:27:51 EST; 3min 32s ago
 Main PID: 960 (django)
    Tasks: 4 (limit: 25028)
   Memory: 95.2M
   CGroup: /system.slice/django.service
           ??960 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a>
           ??964 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a>
           ??965 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a>
           ??966 /usr/bin/python3.6 /usr/local/bin/gunicorn --workers 3 --bind unix:/opt/djangoproject/djangoproject.sock djangoproject.wsgi:a>

Mar 02 22:27:51 centos8 systemd[1]: Started django daemon.
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Starting django 20.0.4
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Listening at: unix:/opt/djangoproject/djangoproject.sock (960)
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [960] [INFO] Using worker: sync
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [964] [INFO] Booting worker with pid: 964
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [965] [INFO] Booting worker with pid: 965
Mar 02 22:27:52 centos8 django[960]: [2020-03-02 22:27:52 -0500] [966] [INFO] Booting worker with pid: 966
h pid: 966

Django용 Nginx 구성

다음으로 Nginx를 Django용 리버스 프록시로 구성해야 합니다. 이렇게 하려면 다음 명령을 사용하여 새 Nginx 구성 파일을 만듭니다.

nano /etc/nginx/conf.d/django.conf

다음 줄을 추가합니다.

server {
    listen 80;
    server_name your-server-ip

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /opt/djangoproject;
    }

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://unix:/opt/djangoproject/djangoproject.sock;
    }
}

완료되면 파일을 저장하고 닫습니다. 그런 다음 다음 명령을 사용하여 구문 오류가 있는지 nginx를 테스트합니다.

nginx -t

모든 것이 정상이면 다음과 같은 결과가 표시됩니다.

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

다음으로 Nginx 서비스를 다시 시작하여 변경 사항을 구현합니다.

systemctl start nginx

다음 명령을 사용하여 Nginx를 확인할 수도 있습니다.

systemctl status nginx

다음과 같은 결과가 표시되어야 합니다.

? nginx.service - The nginx HTTP and reverse proxy server
   Loaded: loaded (/usr/lib/systemd/system/nginx.service; disabled; vendor preset: disabled)
   Active: active (running) since Mon 2020-03-02 22:28:13 EST; 4min 14s ago
  Process: 984 ExecStart=/usr/sbin/nginx (code=exited, status=0/SUCCESS)
  Process: 982 ExecStartPre=/usr/sbin/nginx -t (code=exited, status=0/SUCCESS)
  Process: 980 ExecStartPre=/usr/bin/rm -f /run/nginx.pid (code=exited, status=0/SUCCESS)
 Main PID: 985 (nginx)
    Tasks: 3 (limit: 25028)
   Memory: 5.5M
   CGroup: /system.slice/nginx.service
           ??985 nginx: master process /usr/sbin/nginx
           ??986 nginx: worker process
           ??987 nginx: worker process

Mar 02 22:28:12 centos8 systemd[1]: Starting The nginx HTTP and reverse proxy server...
Mar 02 22:28:12 centos8 nginx[982]: nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
Mar 02 22:28:12 centos8 nginx[982]: nginx: configuration file /etc/nginx/nginx.conf test is successful
Mar 02 22:28:13 centos8 systemd[1]: Started The nginx HTTP and reverse proxy server.

이제 URL http://your-server-ip를 사용하여 Django 애플리케이션에 액세스할 수 있습니다.

결론

이 가이드에서는 CentOS 8에 Django를 설치하는 방법을 배웠습니다. 또한 Gunicorn을 사용하여 Django 서비스를 생성 및 관리하고 Django 애플리케이션을 제공하기 위해 Nginx를 리버스 프록시로 구성하는 방법도 배웠습니다.