Django with Elastic Beanstalk - Settings

Page content

한줄 요약

  • 생각보다 쉽지 않기 때문에 Windows로 하기 보다는 WSL2로 하는 것을 권한다.
    • 이 부분은 추후 업데이트 할 예정이다.

Windows에 EB CLI 설치

C:\WINDOWS\system32>python --version
Python 3.7.4

C:\WINDOWS\system32>pip --version
pip 19.0.3 from c:\users\human\appdata\local\programs\python\python37-32\lib\site-packages\pip (python 3.7)
  • pip을 이용하여 EB CLI를 설치한다.
C:\Windows\System32> pip install awsebcli --upgrade --user
  • 환경변수를 설정한다.
    • Python 3.7 버전으로 설치 했다면, 아래 코드를 환경변수에 추가한다.
%USERPROFILE%\AppData\roaming\Python\Python37\scripts

  • 그리고 시스템 환경에서 eb –version이 나오는지 확인한다.
C:\WINDOWS\system32>eb --version
EB CLI 3.20.3 (Python 3.7.4)

Python 가상환경 설정 및 Django 설치

  • 이름이 eb-virt인 가상환경을 만들고 활성화한다.
$ pip install virtualenv
$ virtualenv eb-virt
$ source eb-virt/Scripts/activate
(eb-virt) $
  • Django를 설치한다.
(eb-virt) $ pip install django
(eb-virt) $ pip freeze
asgiref==3.5.2
Django==3.2.13
pytz==2022.1
sqlparse==0.4.2
typing_extensions==4.2.0

Django 프로젝트 생성

  • Django 프로젝트를 생성한다. 가상환경에 접속을 진행한다.
(eb-virt) $ django-admin startproject ebdjango
(eb-virt) $ cd ebdjango
(eb-virt) ~/ebdjango$ python manage.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 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.
May 20, 2022 - 11:45:19
Django version 3.2.13, using settings 'ebdjango.settings'
Starting development server at http://127.0.0.1:8000/  
Quit the server with CTRL-BREAK.

Elastic Beanstalk에 맞게 Django App 구성

  • 이제 Elastic Beanstalk에 배포하도록 이를 구성한다.
  • 기본적으로 Elastic Beanstalk는 application.py 파일을 찾아 애플리케이션을 시작한다.
  • pip freeze를 실행한 다음 requirements.txt 파일에 출력 저장한다.
(eb-virt) ~/ebdjango$ pip freeze > requirements.txt
  • .ebextensions이라는 디렉터리를 생성한다.
(eb-virt) ~/ebdjango$ mkdir .ebextensions
  • .ebextensions이라는 디렉터리 내에서 다음 텍스트가 있는 django.config 구성 파일을 추가한다.
option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
  • 여기까지 했으면, 가상 환경을 비활성화한다.
$ deactivate
$ tree -a -L 2
.
|-- .ebextensions
|   `-- django.config
|-- db.sqlite3
|-- ebdjango
|   |-- __init__.py
|   |-- __pycache__
|   |-- asgi.py
|   |-- settings.py
|   |-- urls.py
|   `-- wsgi.py
|-- manage.py
`-- requirements.txt

3 directories, 9 files

IAM 사용자

Elastic Beanstalk 프로젝트 구성

  • 먼저 eb init 명령으로 CLI Repo를 초기화한다.
  • eb init을 지정하면 순차적으로 입력하면 된다.
$ eb init

Select a default region
1) us-east-1 : US East (N. Virginia)
2) us-west-1 : US West (N. California)
3) us-west-2 : US West (Oregon)
4) eu-west-1 : EU (Ireland)
5) eu-central-1 : EU (Frankfurt)
6) ap-south-1 : Asia Pacific (Mumbai)
7) ap-southeast-1 : Asia Pacific (Singapore)
8) ap-southeast-2 : Asia Pacific (Sydney)
9) ap-northeast-1 : Asia Pacific (Tokyo)
10) ap-northeast-2 : Asia Pacific (Seoul)
11) sa-east-1 : South America (Sao Paulo)
12) cn-north-1 : China (Beijing)
13) cn-northwest-1 : China (Ningxia)
14) us-east-2 : US East (Ohio)
15) ca-central-1 : Canada (Central)
16) eu-west-2 : EU (London)
17) eu-west-3 : EU (Paris)
18) eu-north-1 : EU (Stockholm)
19) eu-south-1 : EU (Milano)
20) ap-east-1 : Asia Pacific (Hong Kong)
21) me-south-1 : Middle East (Bahrain)
22) af-south-1 : Africa (Cape Town)
(default is 3): 10

You have not yet set up your credentials or your credentials are incorrect
You must provide your credentials.
(aws-access-id): your_id
(aws-secret-key): your_password

Select an application to use
1) humanDjango
2) [ Create new Application ]
(default is 2): 2


Enter Application Name
(default is "ebdjango"): django-tutorial
Application django-tutorial has been created.

It appears you are using Python. Is this correct?
(Y/n): Y
Select a platform branch.
1) Python 3.8 running on 64bit Amazon Linux 2
2) Python 3.7 running on 64bit Amazon Linux 2
3) Python 3.6 running on 64bit Amazon Linux (Deprecated)
(default is 1): 2

Cannot setup CodeCommit because there is no Source Control setup, continuing with initialization
Do you want to set up SSH for your instances?
(Y/n): Y

Type a keypair name.
(Default is aws-eb):
Generating public/private rsa key pair.
Enter passphrase (empty for no passphrase):
Enter same passphrase again: 
Your identification has been saved in C:\Users\human\.ssh\aws-eb
Your public key has been saved in C:\Users\human\.ssh\aws-eb.pub
The key fingerprint is:
SHA256:your_SHA... aws-eb
The key's randomart image is:
+---[RSA 3072]----+
.
.
Enter passphrase: 
WARNING: Uploaded SSH public key for "aws-eb" into EC2 
for region ap-northeast-2.
  • 환경을 만들고 해당 환경에 애플리케이션을 배포 준비를 한다.
    • Elastic Beanstalk 환경을 생성할 때, 약 3-5분가량 소요 됨.
~/ebdjango$ eb create django-env
  • 실제 환경 생성 프로세스가 완료되었는지 확인한다.
~/ebdjango$ eb status
Environment details for: django-env
  Application name: django-tutorial
  Region: ap-northeast-2
  Deployed Version: app-220520_140404219090
  Environment ID: e-zkmutqap2n
  Platform: arn:aws:elasticbeanstalk:ap-northeast-2::platform/Python 3.7 running on 64bit Amazon Linux 2/3.3.13
  Tier: WebServer-Standard-1.0
  CNAME: django-env.eba-fpytmp4i.ap-northeast-2.elasticbeanstalk.com
  Updated: 2022-05-20 05:06:37.415000+00:00
  Status: Ready
  Health: Green

Django 배포

  • 사용자 환경의 도메이 이름은 CNAME에 정의되어 있다.
  • 이제 settings.py를 열고, 이를 ALLOWED_HOSTS에 추가한다.
    • 각자의 CNAME을 등록하면 된다.
ALLOWED_HOSTS = ['eb-django-app-dev.elasticbeanstalk.com']
  • 파일을 저장한 후 배포를 진행한다.
~/ebdjango$ eb deploy
Creating application version archive "app-220520_142411603104".
Uploading django-tutorial/app-220520_142411603104.zip to S3. This may take a while.
Upload Complete.
2022-05-20 05:24:11    INFO    Environment update is starting.
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel2022-05-20 05:24:15    INFO    Deploying new version to instance(s).
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel2022-05-20 05:24:19    INFO    Instance deployment successfully generated a 'Procfile'.
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel2022-05-20 05:24:27    INFO    Instance deployment completed successfully.
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel2022-05-20 05:24:33    INFO    New application version 
was deployed to running EC2 instances.
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel2022-05-20 05:24:33    INFO    Environment update completed successfully.
 -- Events -- (safe to Ctrl+C) Use "eb abort" to cancel
  • 정상적으로 배포가 되었다면 아래와 같이 접속이 되는 것을 확인할 수 있다.

사이트 관리자 생성

  • 우선 로컬 데이터베이스를 초기화해야 한다. +
(eb-virt) ~/ebdjango$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttyp
es, 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...
m 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...    
;1m OK
  Applying auth.0004_alter_user_username_opts...
 OK
  Applying auth.0005_alter_user_last_login_null...     
1m OK
  Applying auth.0006_require_contenttypes_0002...
m 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...
;1m OK
  Applying auth.0011_update_proxy_permissions...       
 OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK
  • 이번에는 관리자를 생성한다.
(eb-virt) ~/ebdjango$ python manage.py createsuperuser
Username (leave blank to use 'human'): admin
Email address: j2hoon85@gmail.com
Password: 
Password (again):
This password is too common.
Bypass password validation and create user anyway? 
[y/N]: y
Superuser created successfully.
  • 정적 파일을 저장할 위치를 Django에 알리려면 STATIC_ROOT에서 settings.py를 정의한다.
import os 
..

STATIC_URL = '/static/'
STATIC_ROOT = "static"
  • 그리고 또한 django.config 파일을 아래와 같이 수정한다.
option_settings:
  aws:elasticbeanstalk:container:python:
    WSGIPath: ebdjango.wsgi:application
  aws:elasticbeanstalk:environment:proxy:staticfiles:
    /static: static
  • 각 static 파일들은 각자 다른 경로에 나눠져 있는다. 이를 하나로 모으도록 한다.
(eb-virt) ~/ebdjango$ python manage.py collectstatic
  • 파일까지 다 모았다면 이제 배포를 진행하도록 한다.
    • 배포 시에는 deactivate 명령어 실행하여 가상환경에서 나와야 한다.
~/ebdjango$ eb deploy
  • 실제 Admin에도 잘 들어가는지 확인한다.