Django 설치 · 6 min read · Dec 22, 2025

Debian 11에 Django 프레임워크 설치하는 방법

Django는 Python으로 작성된 무료 오픈 소스 웹 개발 프레임워크입니다. 복잡하고 데이터베이스 기반의 Python 애플리케이션을 개발하는 데 사용됩니다. Python 프로젝트를 생성하기 위한 Python 스크립트 세트가 함께 제공됩니다. Windows, macOS, Linux/Unix 및 Solaris를 포함하여 Python을 실행할 수 있는 모든 운영 체제에서 실행할 수 있습니다. 개발자가 더 적은 코드를 작성하고 짧은 시간 안에 새로운 웹사이트를 만들 수 있도록 도와줍니다.

이 튜토리얼에서는 Debian 11에서 PostgreSQL 데이터베이스를 사용하여 Python 가상 환경에서 Django를 설정하는 방법을 설명합니다. 그런 다음 Django를 위한 리버스 프록시로 Nginx를 설치하고 구성합니다.

필수 조건

  • Debian 11이 실행되는 서버.
  • 서버 IP를 가리키는 유효한 도메인 이름.
  • 서버에 구성된 루트 비밀번호.

시작하기

시작하기 전에 시스템 패키지를 최신 버전으로 업데이트하는 것이 좋습니다. 다음 명령어를 사용하여 수행할 수 있습니다:

apt-get update -y

모든 패키지가 업데이트되면 다음 명령어를 사용하여 다른 Python 도구와 Nginx 패키지를 설치합니다:

apt-get install python3-pip python3-dev libpq-dev curl nginx -y

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

PostgreSQL 데이터베이스 서버 설치

여기에서는 PostgreSQL을 데이터베이스 백엔드로 사용할 것입니다. 따라서 다음 명령어를 사용하여 설치합시다:

apt-get install postgresql postgresql-contrib -y

PostgreSQL이 설치되면 다음 명령어를 사용하여 PostgreSQL 셸에 연결합니다:

su - postgres  
psql

다음으로, 다음 명령어를 사용하여 Django를 위한 데이터베이스와 사용자를 생성합니다:

CREATE DATABASE django;  
CREATE USER django WITH PASSWORD 'password';

다음으로, 다음 명령어를 사용하여 필요한 역할을 부여합니다:

ALTER ROLE django SET client_encoding TO 'utf8';  
ALTER ROLE django SET default_transaction_isolation TO 'read committed';  
ALTER ROLE django SET timezone TO 'UTC';  
GRANT ALL PRIVILEGES ON DATABASE django TO django;

다음으로, 다음 명령어를 사용하여 PostgreSQL 셸에서 종료합니다:

\q  
exit

이 시점에서 PostgreSQL 데이터베이스는 Django를 위해 준비되었습니다. 이제 다음 단계로 진행할 수 있습니다.

Python 가상 환경 생성

다음으로, Django 프로젝트를 생성하기 위해 Python 가상 환경을 만들어야 합니다.

먼저, 다음 명령어를 사용하여 PIP 패키지를 최신 버전으로 업그레이드합니다:

pip3 install --upgrade pip

다음으로, 다음 명령어를 사용하여 PIP 버전을 확인합니다:

pip --version

샘플 출력:

pip 21.2.4 from /usr/local/lib/python3.9/dist-packages/pip (python 3.9)

다음으로, 다음 명령어를 사용하여 가상 환경 패키지를 설치합니다:

pip3 install virtualenv

다음으로, Django 프로젝트를 위한 디렉토리를 만들고 Django 가상 환경을 생성합니다:

mkdir ~/djangoapp  
cd ~/djangoapp  
virtualenv djangoenv

다음으로, 아래 명령어를 사용하여 Django 가상 환경을 활성화합니다:

source djangoenv/bin/activate

다음으로, 다음 명령어를 사용하여 Django, Gunicorn 및 기타 패키지를 설치합니다:

pip install django gunicorn psycopg2-binary

이 시점에서 Django는 Python 가상 환경에 설치되었습니다. 이제 다음 단계로 진행할 수 있습니다.

Django 설치 및 구성

Django는 프로젝트를 생성하기 위한 django-admin.py 스크립트를 제공합니다. 다음 명령어를 실행하여 Django 프로젝트를 생성할 수 있습니다:

django-admin.py startproject djangoapp ~/djangoapp

다음으로, settings.py를 편집하고 데이터베이스 설정을 정의해야 합니다:

nano ~/djangoapp/djangoapp/settings.py

다음 줄을 도메인 이름으로 변경합니다:

ALLOWED_HOSTS = ['django.example.com', 'localhost']

기본 데이터베이스 백엔드를 주석 해제하고 PostgreSQL 데이터베이스 설정을 추가합니다:

#DATABASES = {
#    'default': {
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': BASE_DIR / 'db.sqlite3',
#    }
#}

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'django',
        'USER': 'django',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',

    }
}

파일의 끝에 다음 줄을 추가합니다:

STATIC_URL = '/static/'
import os
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

파일을 저장하고 닫은 후 초기 데이터베이스 스키마를 PostgreSQL 데이터베이스로 마이그레이션합니다:

./manage.py makemigrations  
./manage.py migrate

샘플 출력:

  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 auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

다음으로, 다음 명령어를 사용하여 Django에 대한 슈퍼유저 계정을 생성합니다:

./manage.py createsuperuser

아래와 같이 관리자 사용자 이름과 비밀번호를 설정합니다:

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

다음으로, 모든 정적 콘텐츠를 디렉토리로 모읍니다:

./manage.py collectstatic

Django 개발 서버 실행

이 시점에서 Django가 설치되고 구성되었습니다. 이제 다음 명령어를 사용하여 Django 개발 서버를 시작할 수 있습니다:

./manage.py runserver 0.0.0.0:8000

모든 것이 정상이라면 다음과 같은 출력을 얻어야 합니다:

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

System check identified no issues (0 silenced).
August 27, 2021 - 10:02:05
Django version 3.2.6, using settings 'djangoapp.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.

이제 웹 브라우저를 열고 URL http://django.example.com:8000/admin/를 사용하여 Django 프로젝트에 접근합니다. Django 로그인 페이지로 리디렉션됩니다:

Django 로그인

관리자 사용자 이름과 비밀번호를 입력하고 로그인을 클릭합니다. 다음 페이지에서 Django 대시보드를 볼 수 있어야 합니다:

Django 관리자 대시보드

이제 터미널로 돌아가서 CTRL + C를 눌러 Django 개발 서버를 중지합니다.

Gunicorn으로 Django 확인

다음으로, Gunicorn이 Django를 제공할 수 있는지 테스트해야 합니다. 다음 명령어를 사용하여 Gunicorn 서버로 Django를 시작할 수 있습니다:

gunicorn --bind 0.0.0.0:8000 djangoapp.wsgi

모든 것이 정상이라면 다음과 같은 출력을 얻어야 합니다:

[2021-08-27 10:04:22 +0000] [47383] [INFO] Starting gunicorn 20.1.0
[2021-08-27 10:04:22 +0000] [47383] [INFO] Listening at: http://0.0.0.0:8000 (47383)
[2021-08-27 10:04:22 +0000] [47383] [INFO] Using worker: sync
[2021-08-27 10:04:22 +0000] [47384] [INFO] Booting worker with pid: 47384

CTRL + C를 눌러 Gunicorn 서버를 중지합니다.

다음으로, 다음 명령어를 사용하여 Python 가상 환경에서 비활성화합니다:

deactivate

Gunicorn을 위한 Systemd 서비스 파일 생성

다음으로, Django 애플리케이션 서버를 시작하고 중지하기 위한 Gunicorn의 systemd 서비스 파일을 생성해야 합니다.

다음 명령어를 사용하여 Gunicorn을 생성할 수 있습니다:

nano /etc/systemd/system/gunicorn.socket

다음 줄을 추가합니다:

[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

파일을 저장하고 닫은 후 Gunicorn에 대한 서비스 파일을 생성합니다:

nano /etc/systemd/system/gunicorn.service

Django 프로젝트 경로에 맞는 다음 줄을 추가합니다:

[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target
[Service]
User=root
Group=www-data
WorkingDirectory=/root/djangoapp
ExecStart=/root/djangoapp/djangoenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock          djangoapp.wsgi:application

[Install]
WantedBy=multi-user.target

파일을 저장하고 닫은 후 Django 프로젝트 디렉토리에 적절한 권한을 설정합니다:

chown -R www-data:root ~/djangoapp

다음으로, 다음 명령어를 사용하여 systemd 데몬을 다시 로드합니다:

systemctl daemon-reload

다음으로, Gunicorn 서비스를 시작하고 시스템 재부팅 시 시작되도록 활성화합니다:

systemctl start gunicorn.socket  
systemctl enable gunicorn.socket

다음으로, 아래 명령어를 사용하여 Gunicorn의 상태를 확인합니다:

systemctl status gunicorn.socket

다음과 같은 출력을 얻어야 합니다:

? gunicorn.socket - gunicorn socket
     Loaded: loaded (/etc/systemd/system/gunicorn.socket; disabled; vendor preset: enabled)
     Active: active (listening) since Fri 2021-08-27 10:05:46 UTC; 6s ago
   Triggers: ? gunicorn.service
     Listen: /run/gunicorn.sock (Stream)
     CGroup: /system.slice/gunicorn.socket

Aug 27 10:05:46 debian11 systemd[1]: Listening on gunicorn socket.

Django를 위한 리버스 프록시로 Nginx 구성

다음으로, Django를 제공하기 위해 Nginx를 리버스 프록시로 구성해야 합니다.

이를 위해 Nginx 구성 파일을 생성합니다:

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

다음 줄을 추가합니다:

server {
     listen 80;
     server_name django.example.com;
    location = /favicon.ico { access_log off; log_not_found off; }


    location /static/ {
         root /root/djangoapp;
     }

    location / {
         include proxy_params;
         proxy_pass http://unix:/run/gunicorn.sock;
     }
}

파일을 저장하고 닫은 후 구성 오류가 있는지 Nginx를 확인합니다:

ginx -t
출력:
ginx: the configuration file /etc/nginx/nginx.conf syntax is ok
ginx: configuration file /etc/nginx/nginx.conf test is successful

마지막으로, 변경 사항을 적용하기 위해 Nginx 서비스를 재시작합니다:

systemctl restart nginx

Nginx의 상태를 확인하려면 다음을 실행합니다:

systemctl status nginx

샘플 출력:

? nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
     Active: active (running) since Fri 2021-08-27 10:06:59 UTC; 6s ago
       Docs: man:nginx(8)
    Process: 47494 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
    Process: 47495 ExecStart=/usr/sbin/nginx -g daemon on; master_process on; (code=exited, status=0/SUCCESS)
   Main PID: 47496 (nginx)
      Tasks: 2 (limit: 2341)
     Memory: 2.5M
        CPU: 49ms
     CGroup: /system.slice/nginx.service
             ??47496 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
             ??47497 nginx: worker process

Aug 27 10:06:59 debian11 systemd[1]: Starting A high performance web server and a reverse proxy server...
Aug 27 10:06:59 debian11 systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argument
Aug 27 10:06:59 debian11 systemd[1]: Started A high performance web server and a reverse proxy server.

이제 URL http://django.example.com/admin를 사용하여 Django 애플리케이션에 접근할 수 있습니다. URL http://django.example.com/를 사용하여 Django 애플리케이션에 접근할 수도 있습니다.

Django 앱

결론

축하합니다! Gunicorn과 Nginx를 리버스 프록시로 사용하여 Django 애플리케이션을 성공적으로 설치했습니다. 이제 Django 프레임워크를 사용하여 Python 애플리케이션을 배포할 수 있습니다.

Share: X/Twitter LinkedIn

새 게시물을 받은 편지함에서 받기

스팸은 없습니다. 언제든지 구독 해지 가능합니다.