ホームページ  >  記事  >  バックエンド開発  >  Hetzner と Dokku を使用して低予算で Django をデプロイする方法

Hetzner と Dokku を使用して低予算で Django をデプロイする方法

WBOY
WBOYオリジナル
2024-08-29 18:33:02240ブラウズ

Django アプリケーションのデプロイは、特に適切なインフラストラクチャを選択する場合に困難になることがあります。

Hetzner と Dokku を組み合わせることで、展開プロセスを容易にする強力で柔軟なソリューションが提供されます。

Docker 上に構築されたサービスとしてのプラットフォーム (PaaS) である Dokku を使用すると、アプリケーションを簡単にデプロイ、管理、拡張できます。

このガイドでは、Dokku を使用して Django アプリケーションを Hetzner にデプロイする方法を説明します。


ヘッツナーとドックとは何ですか?

Hetzner は、専用サーバー、クラウド ホスティング、仮想プライベート サーバー (VPS)、コロケーション サービスなど、さまざまな Web ホスティング サービスを提供するドイツの会社です。

高性能インフラストラクチャを手頃な価格で提供することで知られており、開発者、企業、テクノロジー愛好家の間で人気があります。

Hetzner のデータセンターは主にドイツとフィンランド (ただし、米国と現在はシンガポールにも) にあり、強力なセキュリティ、信頼性、拡張性の高いソリューションを提供しています。

費用対効果の高いクラウド ホスティング オプションが特に好まれており、ヨーロッパのホスティング市場における強力な競争相手となっています。

ドック

Dokku は、Web アプリケーションのデプロイと管理を簡単にするオープンソース ツールです。

Docker を使用し、Heraku と同様に、Git を使用してアプリをデプロイできます。 Dokku は多くのプログラミング言語やフレームワークで動作し、データベースや SSL 証明書などを処理できます。

軽量でサーバー上でのセットアップが簡単なため、より制御性と柔軟性を備えた Heroku のようなセルフホスト型ソリューションを必要とする開発者にとって人気の選択肢となっています。


同じ古い Python コードを書くのに飽きていませんか?プログラミング スキルを次のレベルに引き上げたいですか?もう探す必要はありません。この本は、初心者と経験豊富な Python 開発者にとって同様に究極のリソースです。

「Python のマジック メソッド - initstr を超えた」を入手

マジック メソッドは単なる構文糖ではなく、コードの機能とパフォーマンスを大幅に向上させる強力なツールです。この本では、これらのツールを正しく使用し、Python の可能性を最大限に引き出す方法を学びます。


前提条件

展開プロセスを開始する前に、以下のものがあることを確認してください:

  • Django アプリケーション: Django アプリケーションをデプロイする準備ができている必要があります。これには、requirements.txt ファイルと Procfile が含まれている必要があります。
  • Hetzner Cloud アカウント: お持ちでない場合は、Hetzner でサインアップできます。
  • GitHub アカウント: アプリケーションをデプロイできるようにします。
  • コマンドラインの基本的な知識: ターミナルの使用に慣れている必要があります。

ステップ 1 - Hetzner で VPS を作成する

まず、Hetzner Cloud に VPS (仮想プライベート サーバー) を作成します。アカウントをお持ちでない場合は、ここからサインアップできます。

クラウド コンソールにアクセスしたら:

  • 新しいプロジェクトを作成します。Hetzner Dokku と名付けます。 プロジェクトを入力し、サーバーを追加します。
  • 場所として、ヘルシンキ (EU-central) を選択しましょう。
  • イメージとして、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 をインストールできます。その前に、次のようにして VPS を更新することをお勧めします。

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 Web サイトを確認してください。

デプロイメントプロセスをサポートするいくつかの Docker イメージをプルする必要があるため、これには数分かかる場合があります。

すべてのパッケージがアクティブで実行されていることを確認するために、インストール後にサーバーを再起動する必要があります。

SSH キーと仮想ホストの設定をセットアップする

アプリケーションにアクセスするには、ドメイン名を取得することをお勧めします。ただし、https://slip.io/ でサブドメインをサポートする IP アドレスを使用することもできます。

まず、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 merge (Procfile で定義) を使用してデータベースを移行しました。
  • ガニコーンサーバーを開始しました。

指定された 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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。