Try   HackMD

heroku 佈署網站

  • 申請 heroku 帳號
  • 安裝 git
  • 建立 requirement.txt
  • 建立 Procfile 設定檔
  • 建立 production_settings.py
  • 部署 heroku
  • 參考文件

申請 heroku 帳號及下載 heroku

https://www.heroku.com/ 註冊
下載 heroku cli https://devcenter.heroku.com/articles/heroku-cli#download-and-install

# Linux Debian/Ubuntu
sudo apt install heroku

安裝 git

到 git 官網下載 https://git-scm.com/downloads

#Linux Debian/Ubuntu
sudo apt install git

建立 heroku.yml

setup:                                                                                      
   addons:
     - plan: heroku-postgresql
      as: DATABASE
   config:
     S3_BUCKET: my-example-bucket
 build:
   docker:
     web: Dockerfile
     worker: worker/Dockerfile
   config:
     RAILS_ENV: development
     FOO: bar
 release:
   command:
     - ./deployment-tasks.sh
   image: worker
 run:
   web: bundle exec puma -C config/puma.rb
   worker: python myworker.py
   asset-syncer:
     command:
       - python asset-syncer.py
     image: worker

建立 requirement.txt

建立 requirement.txt 讓 heroku 依照 requirement.txt 安裝套件。
進入 Python 虛礙環境,到專案資料夾,找專案中的原來requirement.txt,將原來的requirement.txt改名,再將使用到的套件列出至 requirement.txt。

(env)$ pip install dj-database-url gunicorn dj-static
(env)$ mv requirement.txt requirement_old.txt
(env)$ pip freeze > requirement.txt

"""
因 heroku 使用PostgreSQL
檢查 requirement.txt psycopg2,
如沒有請加上psycopg2==2.6.1
"""

建立 Procfile 設定檔

Procfile 設定檔是設定 heroku 啟動網站的方式
在專案中 manage.py 的目錄中,建立 Procfile

web: gunicorn  --pythonpath bookstore bookstore.wsgi --log-file -

建立 production_settings.py

通常正式上線(production)時的環境會和開發時所做的settings.py設定有所不同,我們希望網站上線時使用一個全新的、空白的資料庫。
另外建立一個production_settings.py,放在原本的settings.py旁邊

import dj_database_url
from .settings import * # 含入原本的settings.py所有設定
# heroku使用的資料庫為PostgreSQL,所以要修改資料庫設定
DATABASES = {
    'default': dj_database_url.config(),
}
STATIC_ROOT = 'static/' # 設定網站正式上線時靜態檔案目錄位置
ALLOWED_HOSTS = ['*'] # 讓所有的網域都能瀏覽本網站
DEBUG = False # 關閉除錯模式

建立 .gitignore 設定檔

我們不希望把有些開發時使用的檔案,例如虛擬環境、本機資料庫等等。因此,接下來需要建立一個 .gitignore 檔案,排除這些資料:

env # 虛擬環境目錄
*.pyc
__pycache__
db.sqlite3

部署 heroku

在 cli 上登入 heroku,登入剛註冊的帳號

heroku login -i

新增 heroku app

heroku create bookstore

將專案連接到新增的heroku app

heroku git:remote -a bookstore

設定環境變數

heroku config:set DJANGO_SETTINGS_MODULE=bookstore.production_settings

將專案上傳到 heroku

Heroku 使用 Git 管理專案。當我們想把專案上傳到 Heroku 時,必須使用 git push 指令,把專案 push 上去。

$ git add .
$ git commit -m "first commit heroku"
$ git push heroku main

migrate heroku 資料庫

現在 heroku 資料庫是全新的,要先同步及建立superuser

heroku run python bookstore/manage.py migrate
heroku run python bookstore/manage.py createsuperuser

啟動 heroku 網站

heroku ps:scale web=1

開啟網頁

heroku open

修改網站內容

在修改完網站內容後,一樣要透過 git 來更新

$ git add <修改過的檔案>
$ git commit -m "modify"
$ git push heroku main

參考文件