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 es
django_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
-
Inicie sesión en el servidor con un usuario que no sea root sudo usuario a través de SSH.
$ ssh [email protected]
-
instalar
UFW
,Vim
yNginx
con el administrador de paquetes apt.$ sudo apt -y install ufw vim nginx
-
Permitir todo el tráfico saliente.
$ sudo ufw default allow outgoing
-
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
-
Habilitar y recargar
UFW
.$ sudo ufw enable $ sudo ufw reload
2. Instalar PostgreSQL
-
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
-
Cambie al usuario de postgres.
$ sudo su - postgres
-
Inicie sesión en PostgresSQL.
$ psql
-
Cree un rol de base de datos PostgresSQL para el proyecto Django.
postgres=# CREATE ROLE dbuser WITH LOGIN;
-
Establecer contraseña para
dbuser
role.postgres=# password dbuser
-
Establecer
dbuser
codificación aUTF-8
.postgres=# ALTER ROLE dbuser SET client_encoding TO 'utf8';
-
Establecer
dbuser
aislamiento de transacción predeterminado para leer la confirmación.postgres=# ALTER ROLE dbuser SET default_transaction_isolation TO 'read committed';
-
Establecer
dbuser
zona horaria aUTC
.postgres=# ALTER ROLE dbuser SET timezone TO 'UTC';
-
Cree la base de datos del proyecto Django.
postgres=# CREATE DATABASE appdb;
-
otorgar el
dbuser
todos los privilegios paraappdb
.postgres=# GRANT ALL PRIVILEGES ON DATABASE appdb TO dbuser;
-
Exit el cliente postgres.
postgres=# q
-
salir de un sudo
exit
-
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.
-
Instalar el pitón
venv
.$ sudo apt -y install python3-venv
-
Cree el directorio de la aplicación, donde estará el entorno virtual y los archivos de la aplicación. example
app_dir
. Cambie al directorio de inicio.$ cd ~
Cree el directorio.
$ mkdir app_dir
-
Cambiar a
app dir
y crear el entorno virtual.$ cd app_dir $ python3 -m venv venv
-
Activar el entorno virtual.
$ source venv/bin/activate
-
Instalar la biblioteca Python PostgresSQL
psycopg2-binary
en vez depsycopg2
comopsycopg2
tendrá que construirse durante la instalación.$ pip install psycopg2-binary
-
Instale Django y Gunicorn.
$ pip install django gunicorn
4. Cargue o cree el proyecto Django
-
El código fuente del proyecto debe cargarse en el directorio de la aplicación.
app_dir
con git o scp, para este artículo, cree un proyecto de muestra llamadoexample_app
.$ django-admin startproject example_app .
-
Compruebe la estructura de carpetas del
app_dir
.$ ls example_app manage.py venv
-
Cree una carpeta para contener los archivos estáticos del proyecto Django dentro de la carpeta de la aplicación.
$ mkdir static
-
Abre el
settings.py
enexample_app
estafaVim
para configurar el proyecto.$ vim example_app/settings.py
-
Configure el host permitido para el dominio.
ALLOWED_HOSTS = ['mydjango.example.com']
-
Configurar el
DATABASES
variable 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", } }
-
Establezca la ruta de la carpeta estática. Buscar
STATIC_URL
y debajo agregaSTATIC_ROOT
.STATIC_ROOT = "/home/django_user/app_dir/static"
-
Guardar y close la
settings.py
hora de oficina. -
Crear las migraciones del proyecto.
$ python manage.py makemigrations
-
Ejecuta las migraciones.
$ python manage.py migrate
-
Copie todos los archivos estáticos del proyecto a la carpeta estática. Escribe
yes
Cuando se le solicite.$ python manage.py collectstatic
-
Cree un usuario administrador para el proyecto.
$ python manage.py createsuperuser
-
Permitir puerto
8000
enUFW
.$ sudo ufw allow 8000
-
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.
-
Pruebe Gunicorn para ver si puede servir el proyecto sin errores.
$ gunicorn --bind 0.0.0.0:8000 example_app.wsgi
-
Presione CTRL+C para detenerlo.
-
Desactivar el entorno virtual
$ deactivate
-
Editar el
settings.py
archivo conVim
.$ vim example_app/settings.py
-
Deshabilitar depuración. busca la variable
DEBUG
y configúralo enFalse
.DEBUG = False
-
Guardar y close la
settings.py
hora de oficina. -
Denegar el tráfico entrante al puerto 8000 con
UFW
.$ sudo ufw deny 8000
-
Crear un
django_app.service
archivo dentro/etc/systemd/system
directorio.$ sudo vim /etc/systemd/system/django_app.service
-
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_user
establece el usuario del servicio, yGroup=www-data
establece el grupo del servicio en el grupo Nginx. -
WorkingDirectory=/home/django_user/app_dir
establece 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.wsgi
ejecute 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.
-
-
Guardar y close el archivo.
-
Habilite el servicio para que se inicie en el arranque.
$ sudo systemctl enable django_app
-
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.
-
Configure un bloque de servidor en Nginx creando un archivo
django_app
en/etc/nginx/sites-available
.$ sudo vim /etc/nginx/sites-available/django_app
-
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; } }
-
Guardar y close el archivo.
-
Crea un enlace para
django_app
a la de Nginxsites-enabled
.$ sudo ln -s /etc/nginx/sites-available/django_app /etc/nginx/sites-enabled
-
Verifique la configuración de Nginx para ver si hay errores.
$ sudo nginx -t
-
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.
-
instalar
Certbot
con elNginx
enchufar.$ sudo apt install certbot python3-certbot-nginx
-
Para configurar
Certbot
estafaNginx
.$ 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
-
Reanudar
Nginx
.$ sudo systemctl reload nginx
- Visita el dominio del servidor
mydjango.example.com/admin
en 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