首頁 後端開發 Python教學 如何使用 Hetzner 和 Dokku 在預算內部署 Django

如何使用 Hetzner 和 Dokku 在預算內部署 Django

Aug 29, 2024 pm 06:33 PM

部署 Django 應用程式可能具有挑戰性,尤其是在選擇正確的基礎架構時。

Hetzner 與 Dokku 結合,提供了強大且靈活的解決方案,使部署過程變得更加容易。

Dokku 是一個基於 Docker 建置的平台即服務 (PaaS),可讓您輕鬆部署、管理和擴充應用程式。

本指南將向您展示如何使用 Dokku 將 Django 應用程式部署到 Hetzner。


Hetzner 和 Dokku 是什麼?

Hetzner 是一家德國公司,提供各種網站寄存服務,例如專用伺服器、雲端託管、虛擬專用伺服器 (VPS) 和託管服務。

它們以以實惠的價格提供高性能基礎設施而聞名,使其深受開發人員、企業和技術愛好者的歡迎。

Hetzner 的資料中心主要位於德國和芬蘭(還有美國和現在的新加坡),提供強大的安全性、可靠性和可擴展的解決方案。

他們因其經濟高效的雲端託管選項而特別受到青睞,使他們成為歐洲託管市場的強大競爭對手。

多庫

Dokku 是一個開源工具,可以輕鬆部署和管理 Web 應用程式。

它使用 Docker,並允許您使用 Git 部署應用程序,類似於 Heroku。 Dokku 可與多種程式語言和框架配合使用,並且可以處理資料庫、SSL 憑證等。

它輕量級且易於在伺服器上設置,這使其成為想要像 Heroku 這樣的自架解決方案但具有更多控制力和靈活性的開發人員的流行選擇。


您是否厭倦了編寫相同的舊 Python 程式碼?想要將您的程式設計技能提升到一個新的水平嗎?別再猶豫了!本書是初學者和經驗豐富的 Python 開發人員的終極資源。

取得「Python 的神奇方法 - 超越 initstr

魔術方法不僅僅是語法糖,它們是可以顯著提高程式碼功能和效能的強大工具。透過本書,您將學習如何正確使用這些工具並釋放 Python 的全部潛力。


先決條件

在我們開始部署程序之前,請確保您具備以下條件:

  • Django 應用程式:您的 Django 應用程式應該已準備好部署。它應包含一個requirements.txt 檔案和一個Procfile。
  • Hetzner 雲端帳戶:如果您沒有,可以在 Hetzner 註冊。
  • GitHub 帳戶:能夠部署您的應用程式。
  • 基本命令列知識:您應該能夠輕鬆使用終端機。

步驟 1 - 在 Hetzner 中建立 VPS

首先在 Hetzner 雲端中建立 VPS(虛擬專用伺服器)。如果您沒有帳戶,可以在這裡註冊。

進入雲端控制台後:

  • 創建一個新項目,我們將其命名為 Hetzner Dokku。 進入項目並新增伺服器。
  • 對於位置,我們選擇赫爾辛基(歐盟中部)。
  • 對於 Image,我們選擇 Ubuntu 22.04(在撰寫本文時,Dokku 不支援 24.04)
  • 對於類型,我們選擇共享 CPU、x86 和 CX22(2vCPUS、4GB RAM、40GB SSD)。
  • 對於網絡,我們保留 IPv4 和 IPv6。
  • 對於 SSH 金鑰,您應該新增您的 SSH 金鑰。如果沒有,可以使用 ssh-keygen 產生。
  • 您現在可以放棄其他選項。稍後您可以根據需要啟動防火牆。
  • 最後,給它取個名字,在本例中,我們稱之為 dokku-server。

然後按一下「立即建立並購買」。幾秒鐘後,您的 VPS 應該會啟動並運行,並且可以透過指定的 IP 位址透過 SSH 存取:

ssh root@<ip_address>
登入後複製

步驟 2 - 安裝 Dokku

現在 VPS 已配置並運行,您可以安裝 Dokku。在此之前,更新 V​​PS 是一個很好的策略,您可以使用:

apt update && apt upgrade -y
登入後複製

如有必要,請重新啟動 VPS。

安裝 Dokku

您現在可以安裝 Dokku:

wget -NP . https://dokku.com/install/v0.34.8/bootstrap.sh
sudo DOKKU_TAG=v0.34.8 bash bootstrap.sh
登入後複製

在撰寫本文時,最新版本是 v0.34.8。請查看 Dokku 網站以獲取最新版本。

這可能需要幾分鐘,因為它還需要拉取幾個支援部署流程的 Docker 映像。

安裝後您應該重新啟動伺服器,以確保所有軟體包都處於活動狀態並且正在運行。

設定 SSH 金鑰和虛擬主機設置

為了存取應用程序,建議擁有網域名稱。但您也可以使用支援子網域的 IP 位址 https://sslip.io/。

首先,您需要將 SSH 金鑰複製到 Dokku SSH 管理金鑰:

cat ~/.ssh/authorized_keys | dokku ssh-keys:add admin
登入後複製

然後,您可以設定您的網域名稱或IP位址:

dokku domains:set-global <ip_address>.sslip.io
登入後複製

In this case, it defines the IP address, but with support for sub-domains with sslip.io.


Step 3 - Creating the application in Dokku

With Dokku installed and configured, you can now create the application in Dokku that will receive your Django application:

dokku apps:create django-app
登入後複製

This command creates an app called django-app.

Django requires a database and normally there is two choices, either a SQLite or Postgres database.

On Dokku, databases are part of the plugin packages and need to be installed separately:

dokku plugin:install https://github.com/dokku/dokku-postgres.git
登入後複製

This command will install Postgres by downloading the supporting Docker images.

To actually create a database that you can use with the recently created application, you can use the command:

dokku postgres:create django-app-db
登入後複製

Once the the database is created, you will need to link it to the Dokku application:

dokku postgres:link django-app-db django-app
登入後複製

Linked the database to the application means that the database URL is added to the environment variables of the application definitions in Dokku.

You can check that with the command:

dokku config:show django-app
登入後複製

Which should give a similar response to this:

=====> django-app env vars
DATABASE_URL:  postgres://postgres:bca0d7f59caf98c78a74d58457111a1e@dokku-postgres-django-app-db:5432/django_app_db
登入後複製

Step 4 - Creating the Django application

With Dokku installed, configured and an application created, you are now ready to create the actual Django application.

There are several guides on the Internet on how to create a Django application from scratch, so the focus on this article is on deploying the application to Django.

For this tutorial, I created a Django application in PyCharm using the default settings called DjangoAppDokku.

To be able to deploy the application to Dokku, there is some preparation steps that are necessary.

Let's start with making sure there is a requirements file with the command:

pip freeze > requirements.txt
登入後複製
登入後複製

Then you can install some necessary packages to prepare for the Dokku deploying:

pip install python-decouple dj-database-url gunicorn whitenoise psycopg2-binary
登入後複製

This installs three useful packages:

  • python-decouple for managing configuration settings.
  • dj-database-url for simplifying database configuration in Django.
  • gunicorn for serving Python web applications in production.
  • whitenoise to manage access to static files.
  • psycopg2-binary to allow access to Postgres databases.

Now you can create the environment variable file on a file called .env:

DATABASE_URL=sqlite:///db.sqlite3
登入後複製

This configures (for local use) a database URL using SQLite. When the application is deployed to Django it will use the URL defined in Dokku, as we have seen before.

For that to be possible, you need to make some changes in the settings.py file:

import dj_database_url
import os
from decouple import config
from django.conf.global_settings import DATABASES

...

ALLOWED_HOSTS = ['*']

...

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    "whitenoise.middleware.WhiteNoiseMiddleware",
    ... all others middleware ...
]

...

DATABASES['default'] = dj_database_url.parse(config('DATABASE_URL'), conn_max_age=600)

...

STATIC_URL = 'static/'
STATIC_ROOT = BASE_DIR / "static"
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'staticfiles'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage'

登入後複製

This code snippet configures various settings for a Django application:

  • Database Configuration: Uses dj_database_url and decouple to parse the database URL from environment variables.
  • Allowed Hosts: Allows the application to be served from any host (useful for development), but should not be used in Production.
  • Middleware: Includes Django's security middleware and WhiteNoise middleware for serving static files.
  • Static Files: Configures the URL, root directory, additional directories, and storage backend for static files using WhiteNoise.

For Dokku to know how to run the Django application and how to migrate the database, yo will need to create a Procfile:

web: gunicorn DjangoAppDokku.wsgi

release: python manage.py migrate
登入後複製

The Procfile defines two important processes for your Django application, which Dokku will execute:

  • web: gunicorn DjangoAppDokku.wsgi: Starts the Gunicorn web server to handle incoming HTTP requests using the WSGI application defined in DjangoAppDokku.wsgi.
  • release: python manage.py migrate: Runs Django's database migrations as part of the release process, ensuring that the database schema is up-to-date with the latest code changes.

The last set is to make sure that the requirements file is up to date:

pip freeze > requirements.txt
登入後複製
登入後複製

Step 5 - Deploying the Django application to Dokku

With the Django application and the Dokku application prepared, you can now deploy the application to Dokku.

First you will need create a new repository on GitHub then you can add the Django application to it.

So, on your Django project directory, open a terminal and execute these commands:

echo "# DjangoAppDokku" >> README.md
git init
git add .
git commit -m "First Commit"
git branch -M main
git remote add origin [Your GitHub repository URL]
git push -u origin main

登入後複製

Now you add a new git remote for the Dokku server:

git remote add dokku dokku@<your_server_ip>:<your_dokku_app_name>
登入後複製

And finally deploy the application with:

git push dokku
登入後複製

This will produce an output similar to this:

Enumerating objects: 23, done.
Counting objects: 100% (23/23), done.
Delta compression using up to 8 threads
Compressing objects: 100% (21/21), done.
Writing objects: 100% (23/23), 5.48 KiB | 160.00 KiB/s, done.
Total 23 (delta 8), reused 0 (delta 0), pack-reused 0
-----> Cleaning up...
-----> Building django-app from herokuish
-----> Adding BUILD_ENV to build environment...
       BUILD_ENV added successfully
-----> Python app detected
-----> No Python version was specified. Using the buildpack default: python-3.12.5
       To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes
-----> Requirements file has been changed, clearing cached dependencies
-----> Installing python-3.12.5
-----> Installing pip 24.0, setuptools 70.3.0 and wheel 0.43.0
-----> Installing SQLite3
-----> Installing requirements with pip
       Collecting asgiref==3.8.1 (from -r requirements.txt (line 1))
       Downloading asgiref-3.8.1-py3-none-any.whl.metadata (9.3 kB)
       Collecting dj-database-url==2.2.0 (from -r requirements.txt (line 2))
       Downloading dj_database_url-2.2.0-py3-none-any.whl.metadata (12 kB)
       Collecting Django==5.1 (from -r requirements.txt (line 3))
       Downloading Django-5.1-py3-none-any.whl.metadata (4.2 kB)
       Collecting psycopg2-binary==2.9.9 (from -r requirements.txt (line 4))
       Downloading psycopg2_binary-2.9.9-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl.metadata (4.4 kB)
       Collecting python-decouple==3.8 (from -r requirements.txt (line 5))
       Downloading python_decouple-3.8-py3-none-any.whl.metadata (14 kB)
       Collecting sqlparse==0.5.1 (from -r requirements.txt (line 6))
       Downloading sqlparse-0.5.1-py3-none-any.whl.metadata (3.9 kB)
       Collecting typing_extensions==4.12.2 (from -r requirements.txt (line 7))
       Downloading typing_extensions-4.12.2-py3-none-any.whl.metadata (3.0 kB)
       Collecting tzdata==2024.1 (from -r requirements.txt (line 8))
       Downloading tzdata-2024.1-py2.py3-none-any.whl.metadata (1.4 kB)
       Collecting whitenoise==6.7.0 (from -r requirements.txt (line 9))
       Downloading whitenoise-6.7.0-py3-none-any.whl.metadata (3.7 kB)
       Downloading asgiref-3.8.1-py3-none-any.whl (23 kB)
       Downloading dj_database_url-2.2.0-py3-none-any.whl (7.8 kB)
       Downloading Django-5.1-py3-none-any.whl (8.2 MB)
       Downloading psycopg2_binary-2.9.9-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.0 MB)
       Downloading python_decouple-3.8-py3-none-any.whl (9.9 kB)
       Downloading sqlparse-0.5.1-py3-none-any.whl (44 kB)
       Downloading typing_extensions-4.12.2-py3-none-any.whl (37 kB)
       Downloading tzdata-2024.1-py2.py3-none-any.whl (345 kB)
       Downloading whitenoise-6.7.0-py3-none-any.whl (19 kB)
       Installing collected packages: python-decouple, whitenoise, tzdata, typing_extensions, sqlparse, psycopg2-binary, asgiref, Django, dj-database-url
       Successfully installed Django-5.1 asgiref-3.8.1 dj-database-url-2.2.0 psycopg2-binary-2.9.9 python-decouple-3.8 sqlparse-0.5.1 typing_extensions-4.12.2 tzdata-2024.1 whitenoise-6.7.0
-----> $ python manage.py collectstatic --noinput
       System check identified some issues:
       WARNINGS:
       ?: (staticfiles.W004) The directory '/tmp/build/staticfiles' in the STATICFILES_DIRS setting does not exist.
       127 static files copied to '/tmp/build/static'.

-----> Discovering process types
       Procfile declares types -> release, web
-----> Releasing django-app...
-----> Checking for predeploy task
       No predeploy task found, skipping
-----> Checking for release task
       Executing release task from Procfile in ephemeral container: python manage.py migrate
=====> Start of django-app release task (ae9dc2b83) output
remote:  !     System check identified some issues:
remote:  !     WARNINGS:
remote:  !     ?: (staticfiles.W004) The directory '/app/staticfiles' in the STATICFILES_DIRS setting does not exist.
       Operations to perform:
         Apply all migrations: admin, auth, contenttypes, 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... 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... OK
         Applying auth.0004_alter_user_username_opts... OK
         Applying auth.0005_alter_user_last_login_null... OK
         Applying auth.0006_require_contenttypes_0002... 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... OK
         Applying auth.0011_update_proxy_permissions... OK
         Applying auth.0012_alter_user_first_name_max_length... OK
         Applying sessions.0001_initial... OK
=====> End of django-app release task (ae9dc2b83) output
-----> Checking for first deploy postdeploy task
       No first deploy postdeploy task found, skipping
=====> Processing deployment checks
remote:  !     No healthchecks found in app.json for web process type
       No web healthchecks found in app.json. Simple container checks will be performed.
       For more efficient zero downtime deployments, add healthchecks to your app.json. See https://dokku.com/docs/deployment/zero-downtime-deploys/ for examples
-----> Deploying django-app via the docker-local scheduler...
-----> Deploying web (count=1)
       Attempting pre-flight checks (web.1)
-----> Executing 2 healthchecks
       Running healthcheck name='default' type='uptime' uptime=10
       Running healthcheck name='port listening check' attempts=3 port=8000 retries=2 timeout=5 type='listening' wait=5
       Healthcheck succeeded name='port listening check'
       Healthcheck succeeded name='default'
       All checks successful (web.1)
=====> Start of django-app container output (8d55f0f3b481 web.1)
       Python buildpack: Couldn't determine available memory. Skipping automatic configuration of WEB_CONCURRENCY.
       [2024-08-29 08:32:56 +0000] [14] [INFO] Starting gunicorn 23.0.0
       [2024-08-29 08:32:56 +0000] [14] [INFO] Listening at: http://0.0.0.0:8000 (14)
       [2024-08-29 08:32:56 +0000] [14] [INFO] Using worker: sync
       [2024-08-29 08:32:56 +0000] [153] [INFO] Booting worker with pid: 153
=====> End of django-app container output (8d55f0f3b481 web.1)
=====> Triggering early nginx proxy rebuild
-----> Ensuring network configuration is in sync for django-app
-----> Configuring django-app.<ip_address>.sslip.io...(using built-in template)
-----> Creating http nginx.conf
       Reloading nginx
-----> Running post-deploy
-----> Ensuring network configuration is in sync for django-app
-----> Configuring django-app.<ip_address>.sslip.io...(using built-in template)
-----> Creating http nginx.conf
       Reloading nginx

-----> Checking for postdeploy task
       No postdeploy task found, skipping
=====> Application deployed:
       http://django-app.<ip_address>.sslip.io

To <ip_address>:django-app
 * [new branch]      master -> master

登入後複製

Dokku has performed the following actions to deploy the application:

  • 安裝了最新的Python版本。
  • 安裝了requirements.txt 檔案中的要求。
  • 使用 python manage.pycollectstatic --noinput 收集靜態。
  • 使用 python manage.py migrate 遷移資料庫(在 Procfile 中定義)。
  • 啟動了gunicorn伺服器。

如果您現在造訪指定的 URL,您應該會看到熟悉的 Django 預設頁面:

How to Deploy Django on a Budget with Hetzner and Dokku

就是這樣。這就是將 Django 應用程式部署到 Dokku 所需的全部內容。

這些設定非常適合測試應用程式並為測試版使用者提供存取權限,但對於生產用途,您應該向應用程式添加網域並啟用 SSL,請查看 Dokku 文件以獲取更多資訊。


結論

您已使用 Dokku 成功將 Django 應用程式部署到 Hetzner。

得益於 Dokku 簡單而強大的功能,此設定可以輕鬆擴展和管理您的應用程式。

現在您的應用程式已部署,您可以專注於改進和擴展它,因為知道它正在可靠的基礎設施上運行。

以上是如何使用 Hetzner 和 Dokku 在預算內部署 Django的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1658
14
CakePHP 教程
1415
52
Laravel 教程
1309
25
PHP教程
1257
29
C# 教程
1231
24
Python vs.C:申請和用例 Python vs.C:申請和用例 Apr 12, 2025 am 12:01 AM

Python适合数据科学、Web开发和自动化任务,而C 适用于系统编程、游戏开发和嵌入式系统。Python以简洁和强大的生态系统著称,C 则以高性能和底层控制能力闻名。

您可以在2小時內學到多少python? 您可以在2小時內學到多少python? Apr 09, 2025 pm 04:33 PM

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

Python:遊戲,Guis等 Python:遊戲,Guis等 Apr 13, 2025 am 12:14 AM

Python在遊戲和GUI開發中表現出色。 1)遊戲開發使用Pygame,提供繪圖、音頻等功能,適合創建2D遊戲。 2)GUI開發可選擇Tkinter或PyQt,Tkinter簡單易用,PyQt功能豐富,適合專業開發。

2小時的Python計劃:一種現實的方法 2小時的Python計劃:一種現實的方法 Apr 11, 2025 am 12:04 AM

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python與C:學習曲線和易用性 Python與C:學習曲線和易用性 Apr 19, 2025 am 12:20 AM

Python更易學且易用,C 則更強大但複雜。 1.Python語法簡潔,適合初學者,動態類型和自動內存管理使其易用,但可能導致運行時錯誤。 2.C 提供低級控制和高級特性,適合高性能應用,但學習門檻高,需手動管理內存和類型安全。

Python和時間:充分利用您的學習時間 Python和時間:充分利用您的學習時間 Apr 14, 2025 am 12:02 AM

要在有限的時間內最大化學習Python的效率,可以使用Python的datetime、time和schedule模塊。 1.datetime模塊用於記錄和規劃學習時間。 2.time模塊幫助設置學習和休息時間。 3.schedule模塊自動化安排每週學習任務。

Python:探索其主要應用程序 Python:探索其主要應用程序 Apr 10, 2025 am 09:41 AM

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

Python:自動化,腳本和任務管理 Python:自動化,腳本和任務管理 Apr 16, 2025 am 12:14 AM

Python在自動化、腳本編寫和任務管理中表現出色。 1)自動化:通過標準庫如os、shutil實現文件備份。 2)腳本編寫:使用psutil庫監控系統資源。 3)任務管理:利用schedule庫調度任務。 Python的易用性和豐富庫支持使其在這些領域中成為首選工具。

See all articles