Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Heroku에 파이썬 애플리케이션 배포하기: 단계별 완벽 가이드


파이썬으로 개발한 웹 애플리케이션을 클라우드에 올리고 싶다면 Heroku는 가장 빠르고 간편한 선택지 중 하나입니다. 이 글에서는 로컬에서 개발한 파이썬 애플리케이션을 Heroku에 실제로 배포하는 전체 과정을 단계별로 살펴봅니다.

시작하기 전에: 사전 준비 사항

배포를 진행하려면 먼저 로컬 환경에 Python 3.6, Pipenv, Heroku CLI가 설치되어 있어야 하며, 아래 공식 문서의 절차에 따라 CLI에서 Heroku 계정으로 로그인된 상태여야 합니다.

참고 문서: https://devcenter.heroku.com/articles/getting-started-with-python#set-up

1단계: Git 저장소 준비 및 Heroku 앱 생성

Heroku에 애플리케이션을 배포하려면 해당 프로젝트가 Git 저장소로 관리되고 있어야 합니다. 터미널에서 Git 저장소의 루트 디렉터리로 이동한 뒤, 다음 명령어로 새 Heroku 애플리케이션을 생성합니다.

$ heroku create
Creating lit-bastion-5032 in organization heroku... done, stack is cedar-14
https://lit-bastion-5032.herokuapp.com/ | https://git.heroku.com/lit-bastion-5032.git
Git remote heroku added

heroku create 명령을 실행하면 앱이 만들어지는 동시에 heroku라는 이름의 Git 원격(remote)이 자동으로 생성되어 로컬 저장소와 연결됩니다. Heroku는 앱 이름으로 임의의 이름(위 예시에서는 lit-bastion-5032)을 부여하지만, 직접 지정하고 싶다면 명령어 뒤에 원하는 앱 이름을 인자로 넘겨주면 됩니다.

2단계: 코드를 Heroku로 푸시

원격 저장소가 등록되었으므로, 이제 다음 명령어 한 줄이면 코드를 Heroku에 배포할 수 있습니다.

$ git push heroku master
Counting objects: 232, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (217/217), done.
Writing objects: 100% (232/232), 29.64 KiB | 0 bytes/s, done.
Total 232 (delta 118), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.6.0
remote: -----> Installing requirements with latest pipenv...
remote: Installing dependencies from Pipfile.lock...
remote: $ python manage.py collectstatic --noinput
remote: 58 static files copied to '/app/gettingstarted/staticfiles', 58 post-processed.
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 39.3M
remote: -----> Launching...
remote: Released v4
remote: https://lit-bastion-5032.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To git@heroku.com:lit-bastion-5032.git
* [new branch] master -> master

푸시가 완료되면 Heroku가 자동으로 소스 코드를 감지하여 파이썬 런타임과 의존성을 설치하고, 정적 파일을 수집한 후 앱을 실행합니다. 위 로그에서 확인할 수 있듯이 Procfile에 선언된 프로세스 타입(web)을 기준으로 애플리케이션이 구동됩니다.

3단계: requirements.txt로 의존성 관리

배포 시 주의할 점은, 프로젝트에서 사용하는 서드파티 모듈(외부 라이브러리)을 반드시 requirements.txt 파일에 명시해야 한다는 것입니다. 버전 번호를 함께 기재하는 것이 좋으며, 최신 버전을 사용하고 싶다면 버전을 생략해도 무방합니다.

Flask==0.8
Jinja2==2.6
Werkzeug==0.8.3
certifi==0.0.8
chardet==1.0.1

이렇게 작성된 의존성 목록은 배포 과정에서 자동으로 읽혀 필요한 패키지들이 설치됩니다.

마무리

지금까지 Git 저장소 준비부터 heroku create, git push heroku master, 그리고 requirements.txt 작성까지, Heroku에 파이썬 애플리케이션을 배포하는 핵심 과정을 살펴보았습니다. 더 자세한 내용은 Heroku 공식 파이썬 문서(https://devcenter.heroku.com/articles/python-pip)를 참고하시기 바랍니다.