Deploy de Aplicação em Django com uWSGI e Nginx

Deploy de Aplicação em Django com uWSGI e Nginx

Nesse tutorial iremos realizar o deploy de uma aplicação em Django com uWSGI e Nginx

1 – Realizar o update do apt

apt-get update
apt-get upgrade

2 – Instalar dependências

apt install git gcc nginx certbot python3-dev python3.11-venv

3 – Criar diretório do projeto

mkdir /videoaula
cd /videoaula

4 – Criar e ativar o ambiente virtual

python3 -m venv venv
source venv/bin/activate

5 – Instalar os  pacotes

pip install django uwsgi

6 – Iniciar o projeto

python3 -m django --version
django-admin startproject videoaula .
python3 manage.py runserver 0.0.0.0:8000
  • Acesse o host no porta 8000 verifique se aplicação django esta presente.

7 – Ajustar o setting.py

  • Configurar o allowed hosts e a static url
  • Aproveite para checar a aplicação
  • python3 manage.py runserver 0.0.0.0:8000
vim videoaula/settings.py
import os

ALLOWED_HOSTS = ['*']

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")

8 – Testando manualmente o uWSGI

  • Crie um arquivo teste.py com o seguinte conteúdo.
def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World!"]
  • uwsgi –http :8000 –wsgi-file teste.py

Acesse o host na porta 8000 e confirme se o Hello World foi redenrizado.

9 – Testando o projeto vídeo aula com uWSGI usando o IP Socket

  1. Acesse a aplicação via uWSGI para simples conferência.
uwsgi --http :8000 --module videoaula.wsgi

10 – Configurando o Nginx para acessar aplicação via Unix Socket

  • Crie o arquivo .conf dentro de vim /etc/nginx/sites-available/videoaula.conf
  • Preencha com seguinte conteúdo.
# Configuração do Servidor

upstream django {
    server unix:///videoaula/videoaula.sock;
    }


server {
    listen      80;
    server_name videoaula.cuidadodigital.com.br;
    charset     utf-8;
    
    # max upload size
    client_max_body_size 75M;
    
    # Django media and static files
    location /media  {
        alias /videoaula/media;
    }
    #Django static
    location /static {
        alias /videoaula/static;
    }
    # Send all non-media requests to the Django server.
    location / {
        uwsgi_pass  django;
        include     /videoaula/uwsgi_params;
    }
}
  • Crei o uwsgi_params dentro de /video/aula
  • vim /videoaula/uwsgi_params
uwsgi_param  QUERY_STRING       $query_string;
uwsgi_param  REQUEST_METHOD     $request_method;
uwsgi_param  CONTENT_TYPE       $content_type;
uwsgi_param  CONTENT_LENGTH     $content_length;
uwsgi_param  REQUEST_URI        $request_uri;
uwsgi_param  PATH_INFO          $document_uri;
uwsgi_param  DOCUMENT_ROOT      $document_root;
uwsgi_param  SERVER_PROTOCOL    $server_protocol;
uwsgi_param  REQUEST_SCHEME     $scheme;
uwsgi_param  HTTPS              $https if_not_empty;
uwsgi_param  REMOTE_ADDR        $remote_addr;
uwsgi_param  REMOTE_PORT        $remote_port;
uwsgi_param  SERVER_PORT        $server_port;
uwsgi_param  SERVER_NAME        $server_name;
  • Crie um Link Simbólico do videoaula.conf de sites-availabe para sites-enable
ln -s /etc/nginx/sites-available/videoaula.conf /etc/nginx/sites-enabled/
  • Cheque as configurações do ngnix: # ngnix -t
  • Habilite o nginx: # systemct enable nginx
  • Reinicie o nginx: # systemct restart nginx

11 –  Testando aplicação via Unix Socket

uwsgi --socket videoaula.sock --module videoaula.wsgi --chmod-socket=666 --uid www-data
  • Nessa etapa a aplicação ja deve estar funcionando, poém como aplicação e não como serviço

12 – Crei o arquivo de configuração que o demom irá utilizar para chamar uWSGI com serviço

  • vim /videoaula/videoaula_uwsgi.ini
[uwsgi]
# full path to Django project's root directory
chdir = /videoaula
# Django's wsgi file
module = videoaula.wsgi
# full path to python virtual env
home = /videoaula/venv
# enable uwsgi master process
master = true
# maximum number of worker processes
processes = 10
# the socket (use the full path to be safe
socket = /videoaula/videoaula.sock
# socket permissions
chmod-socket = 666
# User ID
uid = www-data
# Group ID
gid = www-data
# clear environment on exit
vacuum = true
# daemonize uwsgi and write messages into given log
daemonize = /videoaula/uwsgi-emperor.log

13 – Testando a aplicação com paramentros de inicialização

uwsgi --ini videoaula_uwsgi.ini

15 – Configurando o vassals

mkdir -p /videoaula/venv/vassals
ln -s /videoaula/videoaula_uwsgi.ini /videoaula/venv/vassals/

16 – Teste final. Realizado teste em modo Emperador do uWSGI emperor mode

uwsgi --emperor /videoaula/venv/vassals --uid www-data --gid www-data

17 – Criando serviço no linux Daemon

  • Crie o arquivo videoaula-uwsgi-emperor.service
  • vim /etc/systemd/system/videoaula-uwsgi-emperor.service
  • Preencha com as seguintes configurações
[Unit]
Description=App Django - Video Aula
After=network.target

[Service]
User=admin
Restart=always
ExecStart=/videoaula/venv/bin/uwsgi --emperor /videoaula/venv/vassals --uid www-data --gid www-data

[Install]
WantedBy=multi-user.target
  • Para habilitar o serviço : systemctl enable videoaula-uwsgi-emperor.service
  • Para iniciar o serviço: systemctl start videoaula-uwsgi-emperor.service

Inpirado em: https://tonyteaches.tech/django-nginx-uwsgi-tutorial/

Sobre o Autor

Diego Elcain administrator