Rumah > Artikel > pembangunan bahagian belakang > Cara Menggunakan Django mengikut Belanjawan dengan Hetzner dan Dokku
Menyediakan aplikasi Django boleh menjadi mencabar, terutamanya apabila memilih infrastruktur yang betul.
Hetzner, digabungkan dengan Dokku, menyediakan penyelesaian yang kukuh dan fleksibel yang menjadikan proses penggunaan lebih mudah.
Dokku, platform-sebagai-perkhidmatan (PaaS) yang dibina pada Docker, membolehkan anda menggunakan, mengurus dan menskalakan aplikasi dengan mudah.
Panduan ini akan menunjukkan kepada anda cara menggunakan aplikasi Django ke Hetzner menggunakan Dokku.
Hetzner ialah syarikat Jerman yang menawarkan pelbagai perkhidmatan pengehosan web, seperti pelayan khusus, pengehosan awan, pelayan peribadi maya (VPS) dan perkhidmatan colocation.
Mereka terkenal kerana menyediakan infrastruktur berprestasi tinggi pada harga yang berpatutan, menjadikannya popular dalam kalangan pembangun, perniagaan dan peminat teknologi.
Pusat data Hetzner terletak terutamanya di Jerman dan Finland (tetapi juga AS dan kini Singapura), menawarkan keselamatan yang kukuh, kebolehpercayaan dan penyelesaian berskala.
Mereka sangat digemari kerana pilihan pengehosan awan yang menjimatkan kos, menjadikan mereka pesaing kuat dalam pasaran pengehosan Eropah.
Dokku ialah alat sumber terbuka yang memudahkan untuk mengatur dan mengurus aplikasi web.
Ia menggunakan Docker dan membolehkan anda menggunakan apl dengan Git, serupa dengan Heroku. Dokku berfungsi dengan banyak bahasa pengaturcaraan dan rangka kerja, dan ia boleh mengendalikan pangkalan data, sijil SSL dan banyak lagi.
Ia ringan dan mudah untuk disediakan pada pelayan, menjadikannya pilihan popular untuk pembangun yang mahukan penyelesaian yang dihoskan sendiri seperti Heroku tetapi dengan lebih kawalan dan fleksibiliti.
Adakah anda bosan menulis kod Python lama yang sama? Ingin meningkatkan kemahiran pengaturcaraan anda ke peringkat seterusnya? Jangan cari lagi! Buku ini ialah sumber terbaik untuk pemula dan pembangun Python yang berpengalaman.
Dapatkan "Kaedah Sihir Python - Melangkaui init dan str"
Kaedah ajaib bukan sekadar gula sintaktik, ia adalah alat berkuasa yang boleh meningkatkan fungsi dan prestasi kod anda dengan ketara. Dengan buku ini, anda akan belajar cara menggunakan alatan ini dengan betul dan membuka kunci potensi penuh Python.
Sebelum kami memulakan proses penempatan, pastikan anda mempunyai perkara berikut:
Mulakan dengan mencipta VPS (Virtual Private Server) dalam Hetzner Cloud. Jika anda tidak mempunyai akaun, anda boleh mendaftar di sini.
Setelah di konsol awan:
Kemudian klik pada Buat & Beli sekarang. Selepas beberapa saat, VPS anda akan berfungsi dan berjalan serta boleh diakses dengan SSH dalam alamat IP yang ditunjukkan:
ssh root@<ip_address>
Sekarang VPS dikonfigurasikan dan berjalan, anda boleh memasang Dokku. Sebelum itu, adalah satu dasar yang baik untuk mengemas kini VPS, yang boleh anda lakukan dengan:
apt update && apt upgrade -y
Jika perlu, mulakan semula VPS.
Anda kini boleh memasang Dokku:
wget -NP . https://dokku.com/install/v0.34.8/bootstrap.sh sudo DOKKU_TAG=v0.34.8 bash bootstrap.sh
Pada masa penulisan, versi terkini ialah v0.34.8. Semak tapak web Dokku untuk versi terkini.
Ini mungkin mengambil masa beberapa minit kerana ia juga perlu menarik beberapa imej Docker yang menyokong proses penempatan.
Anda harus memulakan semula pelayan selepas memasangnya untuk memastikan semua pakej aktif dan berjalan.
Untuk mengakses aplikasi, dinasihatkan untuk mempunyai nama domain. Tetapi anda juga boleh menggunakan alamat IP dengan sokongan subdomain dengan https://sslip.io/.
Pertama, anda perlu menyalin kunci SSH anda ke kunci Pentadbir SSH Dokku:
cat ~/.ssh/authorized_keys | dokku ssh-keys:add admin
Kemudian, anda boleh menetapkan domain atau alamat IP anda:
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.
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
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:
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:
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:
The last set is to make sure that the requirements file is up to date:
pip freeze > requirements.txt
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:
Jika anda kini pergi ke URL yang ditunjukkan, anda akan melihat halaman lalai Django yang biasa:
Dan itu sahaja. Itu sahaja yang diperlukan untuk menggunakan aplikasi Django ke Dokku.
Tetapan ini bagus untuk menguji aplikasi dan menyediakan akses kepada pengguna beta, tetapi untuk penggunaan pengeluaran, anda harus menambahkan nama domain pada aplikasi anda dan mendayakan SSL, semak dokumentasi Dokku untuk mendapatkan maklumat lanjut.
Anda telah berjaya menggunakan aplikasi Django anda kepada Hetzner menggunakan Dokku.
Persediaan ini memudahkan untuk menskala dan mengurus aplikasi anda, terima kasih kepada ciri Dokku yang ringkas namun berkuasa.
Sekarang setelah aplikasi anda digunakan, anda boleh menumpukan pada menambah baik dan mengembangkannya, dengan mengetahui bahawa ia berjalan pada infrastruktur yang boleh dipercayai.
Atas ialah kandungan terperinci Cara Menggunakan Django mengikut Belanjawan dengan Hetzner dan Dokku. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!