跳到主要內容

[Django教學11]Django部署到Heroku雲端平台教學指南

Photo by Christin Hume on Unsplash
在網站開發完成後,不論是網路服務、作品集或網站,為了要讓全世界的使用者可以進行存取使用,就需要部署至雲端平台上,而本文所要分享的Heroku,就是一個非常受歡迎的免費雲端平台,可以用來運行網站或服務。

Heroku支援多種程式語言,使用Git來進行部署,並且提供Heroku CLI(Command Line Interface),來提升部署的效率。本文將示範在Windows作業系統上,部署Django網站到Heroku的過程,分為Django部署準備及部署步驟兩個部份來進行說明,如下:

一、Django部署準備

  1.註冊Heroku帳號
  2.安裝Heroku CLI
  3.安裝Git
  4.安裝gunicorn套件
  5.Django靜態檔案設定
  6.安裝whitenoise套件

二、Django部署步驟

  1.登入Heroku
  2.建立Heroku應用程式
  3.設定Django ALLOWED_HOSTS
  4.建立Git Repository
  5.儲存(commit)程式碼至本地端硬碟(Local Repository)
  6.推送Heroku Git Repository
  7.設定Heroku主機數量
  8.開啟網站

一、Django部署準備

1.註冊Heroku帳號

首先,前往Heroku官網,點擊「SIGN UP FOR FREE」按鈕,依照指示來註冊使用者帳號,如下圖:
2.安裝Heroku CLI

有了Heroku的帳號後,接著前往Heroku Dev Center,來安裝Heroku CLI(Command Line Interface),讓開發人員能夠利用指令的方式,進行Heroku的各種操作,例如登入、建立應用程式及設定等,提升部署Django應用程式的效率。安裝的畫面如下:
選擇相應的作業系統,進行安裝即可。

3.安裝Git

Git是一個分散式的版本控制系統,除了可以協助開發人員進行程式碼的版本控制外,也能夠將程式碼,推送至Heroku雲端平台的Git Repository,來進行部署。

前往Git官網的下載頁面,依照作業系統進行安裝,如下圖:
安裝完成後,開啟命令提示字元視窗,輸入以下指令:

$ git --version

如果有顯示版本號,即代表Git安裝成功。

4.安裝gunicorn套件

gunicornPython應用程式非常受歡迎的網站伺服器套件,所以可以利用它來運行Django網站。可以透過以下指令來安裝:

$ pip install gunicorn

接著,開啟Django專案,新增「Procfile」檔案,Heroku將依據這個檔案中,所設定的網站伺服器,來啟動Django網站,如下圖:
在「Procfile」檔案中,撰寫以下的設定,告訴Heroku雲端平台,利用gunicorn網站伺服器套件,執行Django專案中的wsgi(web server gateway interface)檔案,來啟動網站:

web: gunicorn urexpenses.wsgi


5.Django靜態檔案設定

在開發Django專案的過程中,常常會需要使用到許多的靜態檔案,像是Javascript、CSS及圖片檔等,而這些檔案也需要進行部署。所以,在Django專案中,新增一個資料夾static,來存放靜態檔案,如下圖:
接著,開啟settings.py檔案,新增static資料夾的路徑設定,如下範例:

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

設定完成後,執行以下的指令,就能夠將Django專案中所有應用程式(APP)的靜態檔案,收集至static資料夾中:

$ python manage.py collectstatic

執行結果

6.安裝whitenoise套件

剛剛有提到Django的靜態檔案也需要進行部署,而這些檔案該如何提供給Heroku呢?這時候就可以利用Python的whitenoise套件來達成,透過以下的指令來進行安裝

$ pip install whitenoise

接著,開啟Django專案的settings.py,在MIDDLEWARE串列的地方,加入WhiteNoiseMiddleware,如下範例:
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
有了第3行的設定,當用戶端發出請求,載入Django靜態檔案時,WhiteNoiseMiddleware就會接收,進行靜態檔案的處理。

二、Django部署步驟

以上的前置工作都準備完成,接下來,就可以透過以下8個步驟,將Django網站部署至Heroku雲端平台。

1.登入Heroku
開啟命令提示字元視窗,利用Heroku CLI(Command Line Interface)來進行登入:


$ heroku login


2.建立Heroku應用程式。

$ heroku create <app_name>

執行結果
從執行結果可以看到,左邊為Heroku應用程式的網址,而右邊為對應的Heroku Git Repository,Heroku即是利用這個Git Repository來進行部署的動作

3.設定Django ALLOWED_HOSTS
開啟Django專案的settings.py,將Heroku應用程式的網址(去除https://),設定在ALLOWED_HOSTS的串列中,來允許Heroku的主機存取。
ALLOWED_HOSTS = [
    'urexpenses.herokuapp.com/'
]

4.建立Git Repository
如果此專案已經有Git Repository,則此步驟可省略。

$ git init


5.儲存(commit)程式碼至本地端硬碟(Local Repository)及設定版本說明文字

$ git add .

$ git commit -m "your_message"
6.推送至Heroku Git Repository
這邊教大家一個小技巧,如果在Heroku雲端平台上有多個應用程式時,可以透過以下的指令,來切換Heroku Git Repository

$ heroku git:remote -a <app_name>

Heroku Git Repoistory設定好後,就可以將Django專案程式碼,從本地端硬碟推送到Heroku Git Repoistory

$ git push heroku master


7.設定Heroku主機數量。

$ heroku ps:scale web=1


8.開啟網站。

$ heroku open

執行結果
PSDjango網站部署成功後,未來專案中有任何的異動時,則需重覆執行步驟五及步驟六,將修改的程式碼及檔案,由本地端硬碟(Local Repository)推送至Heroku Git Repository,讓Heroku取得新的程式碼,進而更新網站的執行結果。

三、小結

以上就是Django網站部署至Heroku雲端平台的實作過程,讓各位的網站服務或作品集能夠運行在雲端平台上,供全世界的使用者存取使用。如果在部署的過程中有碰到任何問題,或是文章有說明不清楚的地方,歡迎留言建議及提問唷。

如果您喜歡我的文章,請幫我按五下Like(使用GoogleFacebook帳號免費註冊),支持我創作教學文章,回饋由LikeCoin基金會出資,完全不會花到錢,感謝大家。

有想要看的教學內容嗎?歡迎利用以下的Google表單讓我知道,將有機會成為教學文章,分享給大家😊

你可能有興趣的文章









留言

  1. 請問一下,我在最後push時,出現第九行的錯誤訊息,但是已經裝過asgiref==3.2.7,還是跳Error,不 知道哪邊出錯,請問您有遇過嗎,謝謝。

    remote: -----> Python app detected
    remote: -----> Installing python-3.7.6
    remote: -----> Installing pip
    remote: -----> Installing SQLite3
    remote: -----> Installing requirements with pip
    remote: Collecting asgiref==3.2.7
    remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB)
    remote: Processing /D:/bld/astroid_1588698401017/work
    remote: ERROR: Could not install packages due to an EnvironmentError: [Errno 2] No such file or directory: '/D:/bld/astroid_1588698401017/work'
    remote:
    remote: ! Push rejected, failed to compile Python app.
    remote:
    remote: ! Push failed
    remote: Verifying deploy...
    remote:
    remote: ! Push rejected to mytxx568blog.
    remote:
    To https://git.heroku.com/mytxx568blog.git
    ! [remote rejected] master -> master (pre-receive hook declined)
    error: failed to push some refs to 'https://git.heroku.com/mytxx568blog.git'

    回覆刪除
    回覆
    1. 我找到問題了,因為potrip資料夾,透過 pip freeze > requirements.txt ,輸出了文字檔,裡面的套件名稱後面有加@ ,如下
      asgiref==3.2.7
      astroid @ file:///D:/bld/astroid_1588698401017/work
      autopep8==1.5.2
      ----------------------------------------------------略過

      我把套件名稱後面有加@ file:///D:/bld/astroid_1588698401017/work 刪掉
      再重新heroku上傳就成功了。

      雖然上傳成功,但是不知道為什麼 透過pip freeze > requirements.txt

      為什麼套件後面會加上了 @...這些路徑,還不只一個XD

      刪除
    2. 可能是因為有路徑的關係,所以在產生requirements.txt後,最好還是檢查一下 XD

      刪除
  2. 您好想問執行到git push heroku master這裡
    就跳錯誤了
    remote: ! Push rejected, failed to compile Python app.
    remote:
    remote: ! Push failed
    remote: !
    remote: ! ## Warning - The same version of this code has already been built: 725664b3435e9b14bd368ac8058081fb93cccce2
    remote: !
    remote: ! We have detected that you have triggered a build from source code with version 725664b3435e9b14bd368ac8058081fb93cccce2
    remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch.
    remote: !
    remote: ! If you are developing on a branch and deploying via git you must run:
    remote: !
    remote: ! git push heroku :main
    remote: !
    remote: ! This article goes into details on the behavior:
    remote: ! https://devcenter.heroku.com/articles/duplicate-build-version
    remote:
    remote: Verifying deploy...
    remote:
    remote: ! Push rejected to igcommapp.
    remote:
    To https://git.heroku.com/igcommapp.git
    ! [remote rejected] master -> master (pre-receive hook declined)
    error: failed to push some refs to 'https://git.heroku.com/igcommapp.git'
    想問該怎麼解決 謝謝您 麻煩了

    回覆刪除
    回覆
    1. 已透過粉絲專頁的私訊協助您解決囉~ :)

      刪除
    2. 請問我也遇到相同的error請問要如何解決,感謝您

      刪除
  3. 您好,想請問一下,我還是不太清楚第五步驟,git --commit -m"your message"
    您是寫說是版本的說明,我要去哪裡看呢??

    回覆刪除
    回覆
    1. 您好,git --commit -m "your message"是您可以為這個版本「設定說明文字」,不是用來檢視用,已經有修改文章中的說明,謝謝 :)

      刪除
  4. 您好,想請問一下,第五個步驟的git --commit -m "your message"
    您是寫說版本的說明,請問我要去哪裡看呢??

    回覆刪除
    回覆
    1. 您好,git --commit -m "your message"是您可以為這個版本「設定說明文字」,不是用來檢視用,已經有修改文章中的說明,謝謝 :)

      刪除
  5. windows 用不了gunicorn啊,bash: gunicorn: command not found, 求教這個問題怎麼解決?

    回覆刪除
    回覆
    1. 啊,原來要把Pipfile這個檔案刪了才行

      刪除
  6. 有三個地方希望作者可以更新:
    1. 補上 pip freeze > requitements.txt 的步驟
    2. setting.py 的 DEBUG 改成 False
    3. setting.py 的 SECRET_KEY 最好也改成從環境變數中存取
    雖然只是範例網站而已,但安全性的概念還是要有。

    回覆刪除
  7. 你好我在照著步驟做之後出現了這些錯誤
    我應該要如何解決呢?

    remote: Compressing source files... done.
    remote: Building source:
    remote:
    remote: -----> Building on the Heroku-20 stack
    remote: -----> Determining which buildpack to use for this app
    remote: ! No default language could be detected for this app.
    remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically.
    remote: See https://devcenter.heroku.com/articles/buildpacks
    remote:
    remote: ! Push failed
    remote: Verifying deploy...
    remote:
    remote: ! Push rejected to toadx.
    remote:
    To https://git.heroku.com/toadx.git
    ! [remote rejected] master -> master (pre-receive hook declined)
    error: failed to push some refs to 'https://git.heroku.com/toadx.git'

    回覆刪除
  8. 執行這段以後python manage.py collectstatic
    再deploy到Heroku是錯誤
    然後他有提示我這段
    heroku config:set DISABLE_COLLECTSTATIC=1
    按照指示以後才成功
    請問這是什麼原因呢?

    回覆刪除
  9. 您好,時至今日,Heroku已變為收費。請問是否有其它替代的免費方案方便新手練習?
    我目前手邊有的免費雲端主機是oracle cloud instance,不確定要怎麼用您的教學套用在此平台上。很希望您也可以寫一篇"如何將Django部署到Oracle雲端平台教學指南",謝謝。

    回覆刪除

張貼留言