Comment déployer Django avec un budget limité avec Hetzner et Dokku

WBOY
Libérer: 2024-08-29 18:33:02
original
318 Les gens l'ont consulté

Déployer une application Django peut s'avérer difficile, surtout lors du choix de la bonne infrastructure.

Hetzner, associé à Dokku, fournit une solution solide et flexible qui facilite le processus de déploiement.

Dokku, une plateforme en tant que service (PaaS) basée sur Docker, vous permet de déployer, de gérer et de faire évoluer des applications en toute simplicité.

Ce guide vous montrera comment déployer une application Django sur Hetzner à l'aide de Dokku.


Qu’est-ce que Hetzner et Dokku ?

Hetzner est une société allemande qui propose divers services d'hébergement Web, tels que des serveurs dédiés, l'hébergement cloud, des serveurs privés virtuels (VPS) et des services de colocation.

Ils sont connus pour fournir une infrastructure hautes performances à des prix abordables, ce qui les rend populaires auprès des développeurs, des entreprises et des passionnés de technologie.

Les centres de données Hetzner sont principalement situés en Allemagne et en Finlande (mais aussi aux États-Unis et maintenant à Singapour), offrant une sécurité, une fiabilité et des solutions évolutives élevées.

Ils sont particulièrement appréciés pour leurs options d'hébergement cloud rentables, ce qui en fait un concurrent sérieux sur le marché européen de l'hébergement.

Dokku

Dokku est un outil open source qui facilite le déploiement et la gestion d'applications Web.

Il utilise Docker et vous permet de déployer des applications avec Git, similaires à Heroku. Dokku fonctionne avec de nombreux langages et frameworks de programmation et peut gérer des bases de données, des certificats SSL, etc.

Il est léger et simple à configurer sur un serveur, ce qui en fait un choix populaire pour les développeurs qui souhaitent une solution auto-hébergée comme Heroku mais avec plus de contrôle et de flexibilité.


Vous en avez assez d'écrire le même vieux code Python ? Vous souhaitez faire passer vos compétences en programmation au niveau supérieur ? Ne cherchez plus ! Ce livre est la ressource ultime pour les développeurs Python débutants et expérimentés.

Obtenez "Les méthodes magiques de Python - Au-delà de init et str"

Les méthodes magiques ne sont pas seulement du sucre syntaxique, ce sont des outils puissants qui peuvent améliorer considérablement les fonctionnalités et les performances de votre code. Avec ce livre, vous apprendrez à utiliser correctement ces outils et à libérer tout le potentiel de Python.


Pré-requis

Avant de commencer le processus de déploiement, assurez-vous d'avoir les éléments suivants :

  • Une application Django : votre application Django doit être prête à être déployée. Il doit inclure un fichier requirements.txt et un Procfile.
  • Un compte Hetzner Cloud : si vous n'en avez pas, vous pouvez vous inscrire sur Hetzner.
  • Un compte GitHub : Pour pouvoir déployer votre application.
  • Connaissances de base en ligne de commande : vous devez être à l'aise avec le terminal.

Étape 1 - Créer un VPS dans Hetzner

Commencez par créer un VPS (Virtual Private Server) dans le Hetzner Cloud. Si vous n'avez pas de compte, vous pouvez vous inscrire ici.

Une fois sur la console cloud :

  • Créez un nouveau projet, appelons-le Hetzner Dokku. Entrez le projet et ajoutez un serveur.
  • Pour Localisation, choisissons Helsinki (eu-central).
  • Pour Image, choisissons Ubuntu 22.04 (Dokku ne prend pas en charge 24.04 au moment de la rédaction)
  • Pour Type, nous choisissons CPU partagé, x86 et CX22 (2vCPUS, 4 Go de RAM, 40 Go de SSD).
  • Pour la mise en réseau, nous laissons IPv4 et IPv6 activés.
  • Pour les clés SSH, vous devez ajouter votre clé SSH. Si vous n'en avez pas, vous pouvez le générer avec ssh-keygen.
  • Les autres options que vous pouvez laisser de côté pour le moment. Plus tard, vous pourrez activer un pare-feu si nécessaire.
  • Enfin, donnez-lui un nom, dans ce cas, appelons-le dokku-server.

Cliquez ensuite sur Créer et acheter maintenant. Après quelques secondes, votre VPS devrait être opérationnel et accessible avec SSH à l'adresse IP indiquée :

ssh root@<ip_address>
Copier après la connexion

Étape 2- Installer Dokku

Maintenant que le VPS est configuré et exécuté, vous pouvez installer Dokku. Avant cela, c'est une bonne politique de mettre à jour le VPS, ce que vous pouvez faire avec :

apt update && apt upgrade -y
Copier après la connexion

Si nécessaire, redémarrez le VPS.

Installer Dokku

Vous pouvez maintenant installer Dokku :

wget -NP . https://dokku.com/install/v0.34.8/bootstrap.sh
sudo DOKKU_TAG=v0.34.8 bash bootstrap.sh
Copier après la connexion

Au moment de la rédaction, la dernière version était la v0.34.8. Consultez le site Web Dokku pour la dernière version.

Cela peut prendre quelques minutes, car il faut également extraire quelques images Docker qui prennent en charge le processus de déploiement.

Vous devez redémarrer le serveur après l'avoir installé pour vous assurer que tous les packages sont actifs et en cours d'exécution.

Configurer la clé SSH et les paramètres de l'hôte virtuel

Pour accéder aux applications, il est conseillé de disposer d'un nom de domaine. Mais vous pouvez également utiliser l'adresse IP avec la prise en charge des sous-domaines avec https://sslip.io/.

Tout d'abord, vous devez copier votre clé SSH sur la clé Admin Dokku SSH :

cat ~/.ssh/authorized_keys | dokku ssh-keys:add admin
Copier après la connexion

Ensuite, vous pouvez définir votre domaine ou votre adresse IP :

dokku domains:set-global <ip_address>.sslip.io
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion

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

dokku postgres:link django-app-db django-app
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion
Copier après la connexion

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

pip install python-decouple dj-database-url gunicorn whitenoise psycopg2-binary
Copier après la connexion

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
Copier après la connexion

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'

Copier après la connexion

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
Copier après la connexion

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
Copier après la connexion
Copier après la connexion

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

Copier après la connexion

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

git remote add dokku dokku@<your_server_ip>:<your_dokku_app_name>
Copier après la connexion

And finally deploy the application with:

git push dokku
Copier après la connexion

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

Copier après la connexion

Dokku has performed the following actions to deploy the application:

  • Installé la dernière version de Python.
  • Installé les exigences à partir de votre fichier exigences.txt.
  • Statique collectée avec python manage.py collectstatic --noinput.
  • Migré la base de données avec python manage.py migrate (défini dans le Procfile).
  • Démarrage du serveur gunicorn.

Si vous allez maintenant à l'URL indiquée, vous devriez voir la page par défaut familière de Django :

How to Deploy Django on a Budget with Hetzner and Dokku

Et c'est tout. C'est tout ce qui est nécessaire pour déployer une application Django sur Dokku.

Ces paramètres sont utiles pour tester une application et donner accès aux utilisateurs bêta, mais pour une utilisation en production, vous devez ajouter un nom de domaine à votre application et activer SSL, consultez la documentation Dokku pour plus d'informations.


Conclusion

Vous avez déployé avec succès votre application Django sur Hetzner à l'aide de Dokku.

Cette configuration facilite la mise à l'échelle et la gestion de votre application, grâce aux fonctionnalités simples mais puissantes de Dokku.

Maintenant que votre application est déployée, vous pouvez vous concentrer sur son amélioration et son développement, sachant qu'elle fonctionne sur une infrastructure fiable.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

source:dev.to
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!