Web2py com NGINX

 Neste artigo falaremos sobre como usar o web2py com NGINX.

1º Passo

Em nosso servidor temos o Ubuntu 20.04 Server, vamos nos basear fortemente no script de instalação do web2py setup-web2py-nginx-uwsgi-ubuntu.sh encontrado em scripts na pasta do web2py.

Diferente do Apache o NGINX utiliza o padrão UWSGI enquanto no apache usamos o mod_python, não vamos entrar em detalhes, você pode pesquisar sobre a diferença entre os dois depois.

Você pode começar rodando o script no seu servidor caso esteja usando uma instalação do zero, depois iremos modificar os arquivos de configuração a nossa maneira.

Agora que tudo está instalado é preciso configurar o virtualenv para o projeto.

:~$ virtualenv -p /usr/bin/python3 /opt/venv3

2º Passo

Diferente do apache o NGIX precisa de um "intermediário" que chama o arquivo wsgihandler de cada ambiente. Então vamos começar modificando as instalações que foram feitas no script.

E vamos começar pelo processo uwsgi criado nesse script, modifique-o para que fique como o abaixo.


; Arquivo /etc/systemd/system/emperor.uwsgi.service
[Unit] Description = uWSGI Emperor After = syslog.target [Service] ExecStart = /opt/venv37/bin/uwsgi --emperor /etc/uwsgi/apps-enabled RuntimeDirectory = uwsgi Restart = always KillSignal = SIGQUIT Type = notify StandardError = syslog NotifyAccess = all [Install] WantedBy = multi-user.target

Repare que dentro de [Service] o caminho ExecStart = /usr/local/bin/uwsgi --ini /etc/uwsgi/web2py.ini foi substituído por uma pasta chamada apps-enable ExecStart = /opt/venv37/bin/uwsgi --emperor /etc/uwsgi/apps-enabled e também estou usando o caminho de meu virtualenv que foi criado logo no inicio deste post.

NOTA: Você deve executar um mkdir /etc/uwsgi/apps-enabled, pra funcionar.

3º Passo

E agora vamos criar os arquivos .ini que irão dentro de apps-enable.

; Arquivo /etc/uwsgi/apps-enable/web3py.ini
[uwsgi]

socket = /tmp/web3py.socket
pythonpath = /home/www-data/web3py/
mount = /=wsgihandler:application
processes = 4
master = true
harakiri = 60
reload-mercy = 8
cpu-affinity = 1
stats = /tmp/stats.socket
max-requests = 2000
limit-as = 512
reload-on-as = 256
reload-on-rss = 192
uid = www-data
gid = www-data
touch-reload = /home/www-data/web3py/routes.py
cron = 0 0 -1 -1 -1 /opt/venv37/bin/python /home/www-data/web3py/web2py.py -Q -M -R scripts/sessions2trash.py -A -o
no-orphans = true

O arquivo acima pode ser um modelo para múltiplos ambientes web2py, veja que ele é responsável por associar o virtualenv ao arquivo wsgihandler.py de cada web2py.

Pronto!

4º Passo

Vamos modificar os arquivos em sites-enable dentro do nginx.

# Arquivo /etc/nginx/sites-available/web3py
server {
        listen          80;
        server_name     $hostname;
        ###to enable correct use of response.static_version
        location ~* ^/(\w+)/static(?:/_[\d]+\.[\d]+\.[\d]+)?/(.*)$ {
            alias /home/www-data/web2py/applications/$1/static/$2;
            expires max;
            ### if you want to use pre-gzipped static files (recommended)
            ### check scripts/zip_static_files.py and remove the comments
            # include /etc/nginx/conf.d/web2py/gzip_static.conf;
        }
        ###

        ###if you use something like myapp = dict(languages=['en', 'it', 'jp'], default_language='en') in your routes.py
        #location ~* ^/(\w+)/(en|it|jp)/static/(.*)$ {
        #    alias /home/www-data/web2py/applications/$1/;
        #    try_files static/$2/$3 static/$3 =404;
        #}
        ###
        
        location / {
            #uwsgi_pass      127.0.0.1:9001;
            uwsgi_pass      unix:///tmp/web2py.socket;
            include         uwsgi_params;
            uwsgi_param     UWSGI_SCHEME $scheme;
            uwsgi_param     SERVER_SOFTWARE    nginx/$nginx_version;

            ###remove the comments to turn on if you want gzip compression of your pages
            # include /etc/nginx/conf.d/web2py/gzip.conf;
            ### end gzip section

            ### remove the comments if you use uploads (max 10 MB)
            #client_max_body_size 10m;
            ###
        }
}
server {
        listen 443 default_server ssl;
        server_name     $hostname;
        ssl_certificate         /etc/nginx/ssl/web2py.crt;
        ssl_certificate_key     /etc/nginx/ssl/web2py.key;
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_ciphers ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA;
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        keepalive_timeout    70;
        location / {
            #uwsgi_pass      127.0.0.1:9001;
            uwsgi_pass      unix:///tmp/web2py.socket;
            include         uwsgi_params;
            uwsgi_param     UWSGI_SCHEME $scheme;
            uwsgi_param     SERVER_SOFTWARE    nginx/$nginx_version;
            ###remove the comments to turn on if you want gzip compression of your pages
            # include /etc/nginx/conf.d/web2py/gzip.conf;
            ### end gzip section
            ### remove the comments if you want to enable uploads (max 10 MB)
            #client_max_body_size 10m;
            ###
        }
        ###to enable correct use of response.static_version
        location ~* ^/(\w+)/static(?:/_[\d]+\.[\d]+\.[\d]+)?/(.*)$ {
            alias /home/www-data/web2py/applications/$1/static/$2;
            expires max;
            ### if you want to use pre-gzipped static files (recommended)
            ### check scripts/zip_static_files.py and remove the comments
            # include /etc/nginx/conf.d/web2py/gzip_static.conf;
        }
        ###

}

NOTA: Os certificados ssl foram gerados por openssl, mas você pode muito bem substituí-los por arquivos gerados pelo certbot.

5º Passo

No final de tudo você deve agora abilitar os arquivos de configuração e reiniciar todos os processos.

# ln -s /etc/nginx/sites-available/web3py.conf /etc/nginx/sites-enabled/web3py
# ln -s /etc/uwsgi/apps-available/web3py.ini /etc/uwsgi/apps-enabled/web3py.ini
# /etc/init.d/nginx start


Referencias

Os arquivos /etc/uwsgi são como os arquivos .conf do apache e nginx.

https://groups.google.com/g/web2py/c/o6qB1ROywro/m/MdBUr_ybShsJ

Baseado nesse arqtigo do django pecisa mudar uma configuração no [service] exectstart de --ini para --emperor

https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-uwsgi-and-nginx-on-debian-8

Parece também que para usar BLOCKS (VIRTUALHOSTS) somente um listem pode ser o default_server listem [::]:80 default_server

https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-16-04

Comentários

  1. NOTA: Como criamos um virtualenv pode ser que o uwsgi não esteja instalado na pasta /opt/venv37/bin/uwsgi.

    Você deve executar um /opt/venv37/bin/pip3.7 install uwsgi

    ResponderExcluir
  2. E também, tente desinstalar e instalar as versões do python, remova tudo.
    apt-get autoremove python-dev python-virtualenv python2.7
    pip uninstall uwsgi
    ....

    Depois refaça o processo de instalação com python3.
    apt-get install python3-dev python3-virtualenv

    ResponderExcluir

Postar um comentário

Postagens mais visitadas deste blog

Configurar o web2py no Apache e Ubuntu LTS

Limpando a sujeira para fazer backup

Recursive select with web2py