首頁  >  文章  >  後端開發  >  如何使用 Hetzner 和 Dokku 在預算內部署 Django

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

WBOY
WBOY原創
2024-08-29 18:33:02242瀏覽

部署 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