[Wagtail]을 Heroku에 배포해보자.

DARTZ·2022년 3월 20일
0

Django, Wagtail

목록 보기
2/5
post-thumbnail

서론

강의

문서

Heroku란?

웹사이트를 만들고 나면 배포를 해보고 싶을 것이다. 인터넷에 배포를 검색해보면 Docker, AWS등을 만나게 된다. 관련 튜토리얼을 찾고 배포를 하려고 보면 만만치 않다는 것을 깨달을 것이다.

그렇다면 나는 간단하게만 배포를 해보고 싶은데 방법이 없을까? 한다면 Heroku가 정답이 될 수 있다. 위키를 살펴보면 Heroku는 웹 애플리케이션 배치 모델로 사용되는 여러 프로그래밍 언어를 지원하는 클라우드 PaaS라고 설명이 되어 있다. 여기서 Paas란 서비스형 플랫폼(Platform as a Service, PaaS)의 약자로 일반적으로 앱을 개발하거나 구현할 때, 관련 인프라를 만들고 유지보수하는 복잡함 없이 애플리케이션을 개발, 실행, 관리할 수 있게 하는 플랫폼을 제공한다.

간단하게 웹사이트를 배포할 수 있게 도와주는 플랫폼이라고 생각하면된다.

내가 사용하는 Django 기반 CMS인 Wagtail을 Heroku를 통해 배포하는 방법을 알아보려 한다.
기준은 Window 기준으로 적어보려고 한다.

본론

1. Heroku 설치

https://devcenter.heroku.com/articles/heroku-cli

먼저 위에 사이트에서 운영체제에 맞는 Heroku를 다운 받도록 하자.

2. 라이브러리 설치

pip install 
django
psycopg2-binary
gunicorn
dj-database-url
dj-static

배포에 필요한 라이브러리를 설치하고

pip freeze > requirements.txt

requirements.txt파일을 업데이트 해준다.

3. 데이터 베이스 설정 (PostgreSQL)

기존에 사용하던 SQLite 대신 PostgreSQL로 바꿔주자.

set PGUSER=postgres
psql
psql -U postgres
CREATE USER test_user WITH PASSWORD '123';
CREATE DATABASE test_db OWNER test_user;

settings/base.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'test_db',
        'USER': 'test_user',
        'PASSWORD': '123',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

간단한 배포를 위해 base.py에 정의하지만 실제 production에서는 보안을 위해 .env 파일에 정의해줘야한다.

4. Procfile 생성

Procfile

web: gunicorn 프로젝트이름.wsgi --log-file -

5. runtime.txt 파일 생성

https://devcenter.heroku.com/articles/python-support

위의 사이트에서 지원되는 파이썬 버전을 확인해 볼 수 있다.

runtime.txt

python-3.8.12

나는 프로젝트에서 사용한 3.8.12버전으로 진행해보겠다.

6. settings/production.py 수정

settings/production.py

# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config()
	
# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

아직 Heroku url을 모르기 때문에 ALLOWED_HOSTS는 모두 허용을 해놓는다.

7. .gitIgnore 파일 생성

.gitignore

*.pyc
.DS_Store
*.swp
/venv/
/static/
/media/
.env

이미 git에 연결했으면 .gitignore파일이 존재할 것이다. 위의 내용을 추가해주자.

8. .env 파일생성

.env

DJANGO_SETTINGS_MODULE=project_title.settings.production
SECRET_KEY='####'

env 파일 작성이다. 데이터 베이스 정보를 이곳에 입력하고 os.environ.copy()를 통해 데이터베이스를 정의해주면 된다.

9. Production.py 파일 수정

settings/production.py

from __future__ import absolute_import, unicode_literals
from .base import *
import dj_database_url
import os


env = os.environ.copy()
SECRET_KEY = env['SECRET_KEY']

중요한 것은 future은 제일 먼저 import 되어야 하므로 맨 위에 적는다.

10. Heroku 배포

배포전에 git에 push를 해놓자!!

git init
git add .
git commit -m "first commit to heroku"
heroku create 
# Creates a new Heroku app and connects it to your initialised git repo
git push heroku master 
# Pushes your commited code up to your new ap
heroku plugins:install heroku-config
# Install plugin that allows us to push settings to heroku
heroku config:push
# Pushes settings to heroku, if you get an error check your spaces.
heroku run python manage.py migrate 
# Heroku allows you to run shell commands remotely with the 'heroku run' command.
heroku run python manage.py createsuperuser
# Creates a new superuser on Heroku
heroku ps:scale web=1 
# Ensures that a new Dyno is running for your project

글쓴이 issue)

user모델을 custom model로 사용해서

Dependency on app with no migrations: user 오류가 발생했다.

user app의 migrations폴더에 0001_initial.py을 .gitignore에 포함시키고 git push를 해주면 된다.

user app에 user model이 정의 되어 있는데 diary app에서 user를 사용하기 때문에 dependency오류가 발생하는 것 같다.

11. whitenoise제거

pip install whitenoise

settings/base.py

MIDDLEWARE = [

	...
    'whitenoise.middleware.WhiteNoiseMiddleware',

]

settings/production.py

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

COMPRESS_OFFLINE = True
COMPRESS_CSS_FILTERS = [
    'compressor.filters.css_default.CssAbsoluteFilter',
    'compressor.filters.cssmin.CSSMinFilter',
]
COMPRESS_CSS_HASHING_METHOD = 'content'
git push heroku master

heroku에 대한 자세한 설명이 보고싶다면

heroku help

중요!!!
Heroku에서는 Local에서 makemigrations를 진행하고 migrations 파일까지 전부 git에 업로드 해야한다. 그리고 heroku에서 migrate를 해줘야한다.

profile
사람들이 비용을 지불하고 사용할 만큼 가치를 주는 서비스를 만들고 싶습니다.

0개의 댓글