Usando Django con Nginx, PostgreSQL y Gunicorn en Debian 11

Introducción

Djangoes un marco web de Python gratuito y de código abierto. Este artículo proporciona una guía paso a paso para configurar un proyecto Django en un servidor Debian 11 con Nginx, Gunicorn y un certificado TLS gratuito de Let’s Encrypt.

requisitos previos

  • Implemente un nuevo servidor Debain 11 en Vultr

  • Crear un sudo usuario. los example el usuario esdjango_user

  • Actualizar el servidor

  • Apunte un nombre de dominio al servidor. Se requiere un nombre de dominio para los certificados Let’s Encrypt SSL/TLS. Esta guía utiliza el dominio de vérticeejemplo.comy el nombre de dominio completomidjango.ejemplo.comy asume que se asigna la misma dirección IP a ambos nombres.

1. Instalar dependencias

  1. Inicie sesión en el servidor con un usuario que no sea root sudo usuario a través de SSH.

    $ ssh [email protected]
    
  2. instalarUFW,VimyNginxcon el administrador de paquetes apt.

    $ sudo apt -y install ufw vim nginx
    
  3. Permitir todo el tráfico saliente.

    $ sudo ufw default allow outgoing
    
  4. Bloquee todo el tráfico entrante excepto SSH (puerto 22), HTTP (puerto 80) y HTTPS (puerto 443).

    $ sudo ufw default deny incoming
    
    $ sudo ufw allow ssh
    
    $ sudo ufw allow http
    
    $ sudo ufw allow https
    
  5. Habilitar y recargarUFW.

    $ sudo ufw enable
    
    $ sudo ufw reload
    

2. Instalar PostgreSQL

  1. Instale PostgreSQL con el administrador de paquetes apt, se crea un usuario de postgres durante la instalación.

    $ sudo apt install -y postgresql postgresql-contrib
    
  2. Cambie al usuario de postgres.

    $ sudo su - postgres
    
  3. Inicie sesión en PostgresSQL.

    $ psql
    
  4. Cree un rol de base de datos PostgresSQL para el proyecto Django.

    postgres=# CREATE ROLE dbuser WITH LOGIN;
    
  5. Establecer contraseña paradbuserrole.

    postgres=# password dbuser
    
  6. Establecerdbusercodificación aUTF-8.

    postgres=# ALTER ROLE dbuser SET client_encoding TO 'utf8';
    
  7. Establecerdbuseraislamiento de transacción predeterminado para leer la confirmación.

    postgres=# ALTER ROLE dbuser SET default_transaction_isolation TO 'read committed';
    
  8. Establecerdbuserzona horaria aUTC.

    postgres=# ALTER ROLE dbuser SET timezone TO 'UTC';
    
  9. Cree la base de datos del proyecto Django.

    postgres=# CREATE DATABASE appdb;
    
  10. otorgar eldbusertodos los privilegios paraappdb.

    postgres=# GRANT ALL PRIVILEGES ON DATABASE appdb TO dbuser;
    
  11. Exit el cliente postgres.

    postgres=# q
    
  12. salir de un sudo

    exit
    
  13. Reinicie el servidor PostgresSQL.

    $ sudo systemctl restart postgresql
    

3. Configurar el entorno de Python

Se debe usar un entorno virtual de Python al implementar aplicaciones web de Python.

  1. Instalar el pitónvenv.

    $ sudo apt -y install python3-venv
    
  2. Cree el directorio de la aplicación, donde estará el entorno virtual y los archivos de la aplicación. exampleapp_dir. Cambie al directorio de inicio.

    $ cd ~
    

    Cree el directorio.

    $ mkdir app_dir
    
  3. Cambiar aapp diry crear el entorno virtual.

    $ cd app_dir
    
    $ python3 -m venv venv
    
  4. Activar el entorno virtual.

    $ source venv/bin/activate
    
  5. Instalar la biblioteca Python PostgresSQLpsycopg2-binaryen vez depsycopg2comopsycopg2tendrá que construirse durante la instalación.

    $ pip install psycopg2-binary
    
  6. Instale Django y Gunicorn.

    $ pip install django gunicorn
    

4. Cargue o cree el proyecto Django

  1. El código fuente del proyecto debe cargarse en el directorio de la aplicación.app_dircon git o scp, para este artículo, cree un proyecto de muestra llamadoexample_app.

    $ django-admin startproject example_app .
    
  2. Compruebe la estructura de carpetas delapp_dir.

    $ ls
    
    example_app manage.py venv
    
  3. Cree una carpeta para contener los archivos estáticos del proyecto Django dentro de la carpeta de la aplicación.

    $ mkdir static
    
  4. Abre elsettings.pyenexample_appestafaVimpara configurar el proyecto.

    $ vim example_app/settings.py
    
  5. Configure el host permitido para el dominio.

    ALLOWED_HOSTS = ['mydjango.example.com']
    
  6. Configurar elDATABASESvariable con los detalles creados a partir desection 2.

    DATABASES = {
    
        "default" : {
    
            "ENGINE" : "django.db.backends.postgresql",
    
            "NAME" : "appdb",
    
            "USER" : "dbuser",
    
    
    
            "PASSWORD" : "dbpassword",
    
    
    
            "HOST" : "127.0.0.1",              
    
            "PORT" : "5432",
    
    
    
            }
    
    }
    
  7. Establezca la ruta de la carpeta estática. BuscarSTATIC_URLy debajo agregaSTATIC_ROOT.

    STATIC_ROOT = "/home/django_user/app_dir/static"
    
  8. Guardar y close lasettings.pyhora de oficina.

  9. Crear las migraciones del proyecto.

    $ python manage.py makemigrations
    
  10. Ejecuta las migraciones.

    $ python manage.py migrate
    
  11. Copie todos los archivos estáticos del proyecto a la carpeta estática. EscribeyesCuando se le solicite.

    $ python manage.py collectstatic
    
  12. Cree un usuario administrador para el proyecto.

    $ python manage.py createsuperuser
    
  13. Permitir puerto8000enUFW.

    $ sudo ufw allow 8000
    
  14. Pruebe el proyecto para asegurarse de que se ejecuta sin errores.

    $ python manage.py runserver 0.0.0.0:8000
    
    
    
    Watching for file changes with StatReloader
    
    Performing system checks...
    
    
    
    System check identified no issues (0 silenced).
    
    November 16, 2022 - 21:19:26
    
    Django version 4.1.3, using settings 'example_app.settings'
    
    Starting development server at https://0.0.0.0:8000/
    
    Quit the server with CONTROL-C.
    

5. Configurar Gunicorn

Se creará un servicio Gunicorn para atender el proyecto e iniciar el proyecto en los reinicios del servidor.

  1. Pruebe Gunicorn para ver si puede servir el proyecto sin errores.

    $ gunicorn --bind 0.0.0.0:8000 example_app.wsgi
    
  2. Presione CTRL+C para detenerlo.

  3. Desactivar el entorno virtual

    $ deactivate
    
  4. Editar elsettings.pyarchivo conVim.

    $ vim example_app/settings.py
    
  5. Deshabilitar depuración. busca la variableDEBUGy configúralo enFalse.

    DEBUG = False
    
  6. Guardar y close lasettings.pyhora de oficina.

  7. Denegar el tráfico entrante al puerto 8000 conUFW.

    $ sudo ufw deny 8000
    
  8. Crear undjango_app.servicearchivo dentro/etc/systemd/systemdirectorio.

    $ sudo vim /etc/systemd/system/django_app.service
    
  9. Escriba lo siguiente en el archivo.

    [Unit]
    
    
    
    Description=Gunicorn for the Django project
    
    After=network.target
    
    
    
    [Service]
    
    
    
    User=django_user
    
    Group=www-data
    
    
    
    
    
    WorkingDirectory=/home/django_user/app_dir
    
    Environment="PATH=/home/django_user/app_dir/venv/bin"
    
    ExecStart=/home/django_user/app_dir/venv/bin/gunicorn --workers 2 --bind unix:django_app.sock example_app.wsgi
    
    
    
    
    
    [Install]
    
    
    
    WantedBy=multi-user.target
    
    • Por debajo[Service],USER=django_userestablece el usuario del servicio, yGroup=www-dataestablece el grupo del servicio en el grupo Nginx.

    • WorkingDirectory=/home/django_user/app_direstablece el directorio de trabajo del servicio en la carpeta de proyectos.

    • Environment="PATH=/home/django_user/app_dir/venv/bin"establece el entorno virtual que debe usar el servicio.

    • ExecStart=/home/django_user/app_dir/venv/bin/gunicorn --workers 2 --bind unix:django_app.sock example_app.wsgiejecute los servicios de trabajo de gunicorn para el proyecto y los vincula a un socket Unix para un intercambio de datos más rápido para el servidor proxy Nginx.

  10. Guardar y close el archivo.

  11. Habilite el servicio para que se inicie en el arranque.

    $ sudo systemctl enable django_app
    
  12. Inicie el servicio.

    $ sudo systemctl start django_app
    

6. Configurar Nginx

Se necesita un servidor proxy Nginx para servir aplicaciones de Django en producción y para manejar certificados SSL.

  1. Configure un bloque de servidor en Nginx creando un archivodjango_appen/etc/nginx/sites-available.

    $ sudo vim /etc/nginx/sites-available/django_app
    
  2. Escriba lo siguiente en el archivo.

    server {
    
        # listen to port 80 (HTTP)
    
        listen 80;
    
        # listen to the domain name
    
        server_name example.com mydjango.example.com;
    
    
    
        location /static/ {
    
            alias /home/django_user/app_dir/static/;
    
            expires max;
    
        }
    
    
    
        location / {
    
            include proxy_params;
    
    
    
            # pass the request to the project service sock
    
            proxy_pass https://unix:/home/django_user/app_dir/django_app.sock;
    
        }
    
    }
    
  3. Guardar y close el archivo.

  4. Crea un enlace paradjango_appa la de Nginxsites-enabled.

    $ sudo ln -s /etc/nginx/sites-available/django_app /etc/nginx/sites-enabled
    
  5. Verifique la configuración de Nginx para ver si hay errores.

    $ sudo nginx -t
    
  6. Reinicie el servidor Nginx.

    $ sudo systemctl reload nginx
    

7. (Opcional) Agregue HTTPS con Let’s Encrypt

Si configuró un dominio al principio, puede agregar un certificado SSL/TLS con Let’s Encrypt para proporcionar compatibilidad con HTTPS.

  1. instalarCertbotcon elNginxenchufar.

    $ sudo apt install certbot python3-certbot-nginx
    
  2. Para configurarCertbotestafaNginx.

    $ sudo certbot --nginx -d example.com -d mydjango.example.com
    

    La primera vez que ejecuté Certbot, un admin Se solicitará el correo electrónico para los certificados. Certbot también configurará Nginx y redirigirá todas las solicitudes HTTP a HTTPS configurando el bloque del servidor.

    Saving debug log to /var/log/letsencrypt/letsencrypt.log
    
    Plugins selected: Authenticator nginx, Installer nginx
    
    Enter email address (used for urgent renewal and security notices)
    
     (Enter 'c' to cancel): [email protected]
    
    
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    Please read the Terms of Service at
    
    https://letsencrypt.org/documents/LE-SA-v1.3-September-21-2022.pdf. You must
    
    agree in order to register with the ACME server. Do you agree?
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    (Y)es/(N)o: y
    
    
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    Would you be willing, once your first certificate is successfully issued, to
    
    share your email address with the Electronic Frontier Foundation, a founding
    
    partner of the Let's Encrypt project and the non-profit organization that
    
    develops Certbot? We'd like to send you email about our work encrypting the web,
    
    EFF news, campaigns, and ways to support digital freedom.
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    (Y)es/(N)o: y
    
    Account registered.
    
    Requesting a certificate for example.com and mydjango.example.com
    
    Performing the following challenges:
    
    http-01 challenge for example.com
    
    http-01 challenge for mydjango.example.com
    
    Waiting for verification...
    
    Cleaning up challenges
    
    Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/django_app
    
    Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/django_app
    
    Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/django_app
    
    Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/django_app
    
    
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    Congratulations! You have successfully enabled https://example.com and
    
    https://mydjango.example.com
    
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    Subscribe to the EFF mailing list (email: [email protected]).
    
    
    
    IMPORTANT NOTES:
    
     - Congratulations! Your certificate and chain have been saved at:
    
       /etc/letsencrypt/live/example.com/fullchain.pem
    
       Your key file has been saved at:
    
       /etc/letsencrypt/live/example.com/privkey.pem
    
       Your certificate will expire on 2023-02-15. To obtain a new or
    
       tweaked version of this certificate in the future, simply run
    
       certbot again with the "certonly" option. To non-interactively
    
       renew *all* of your certificates, run "certbot renew"
    
     - If you like Certbot, please consider supporting our work by:
    
    
    
       Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
    
       Donating to EFF:                    https://eff.org/donate-le
    
  3. ReanudarNginx.

    $ sudo systemctl reload nginx
    
  • Visita el dominio del servidormydjango.example.com/adminen tu navegador.

Ahora tiene un sitio de Django en funcionamiento en Debian 11.

Título del artículo Nombre (opcional) Correo electrónico (opcional) Descripción

Enviar sugerencia

Artículos Relacionados