| Author: Eduardo Enriquez

Cómo configurar nginx - gunicorn - django

NGINX

Para configurar nginx es necesario, en primer lugar, crear un archivo específico para nuestro sitio web, esto es, un archivo de configuración para nuestro proyecto:

sudo touch /etc/nginx/sites-available/myproject

 

Luego al editarlo podemos poner una configuración básica:

sudo vim /etc/nginx/sites-available/myproject

Este archivo de configuración sirve para levantar el "server" que se va a encargar de servir (de entregar) los archivos estaticos que nos lleguen a nuestro servidor. Ahora bien, un server puede alojar multiples sitios.  Para indicarle, los pedidos, requests, de nuestro dominio en particular se indica el "server_name", que puede ser un dominio o una direccion ip válida:

 
server { 
    listen 80; 
    server_name www.midominio.com dominio.com 192.168.1.15; 
}

Las configuraciones de nginx son muchas, porque no solo sirve para alojar sitios de Django, sino porque puede ser utilizado como proxy o como muchas cosas mas. Una configuración más compleja podría ser por ejemplo la siguiente:

 	
worker_processes 1;

user nobody nogroup;
# 'user nobody nobody;' for systems with 'nobody' as a group instead
pid /tmp/nginx.pid;
error_log /tmp/nginx.error.log;

events {
  worker_connections 1024; # increase if you have lots of clients
  accept_mutex off; # set to 'on' if nginx worker_processes > 1
  # 'use epoll;' to enable for Linux 2.6+
  # 'use kqueue;' to enable for FreeBSD, OSX
}

http {
  include mime.types;
  # fallback in case we can't determine a type
  default_type application/octet-stream;
  access_log /tmp/nginx.access.log combined;
  sendfile on;

  upstream app_server {
    # fail_timeout=0 means we always retry an upstream even if it failed
    # to return a good HTTP response

    # for UNIX domain socket setups
    server unix:/tmp/gunicorn.sock fail_timeout=0;

    # for a TCP configuration
    # server 192.168.0.7:8000 fail_timeout=0;
  }

  server {
    # if no Host match, close the connection to prevent host spoofing
    listen 80 default_server;
    return 444;
  }

  server {
    # use 'listen 80 deferred;' for Linux
    # use 'listen 80 accept_filter=httpready;' for FreeBSD
    listen 80;
    client_max_body_size 4G;

    # set the correct host(s) for your site
    server_name example.com www.example.com;

    keepalive_timeout 5;

    # path for static files
    root /path/to/app/current/public;

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @proxy_to_app;
    }

    location @proxy_to_app {
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      # enable this if and only if you use HTTPS
      # proxy_set_header X-Forwarded-Proto https;
      proxy_set_header Host $http_host;
      # we don't want nginx trying to do something clever with
      # redirects, we set the Host: header above already.
      proxy_redirect off;
      proxy_pass http://app_server;
    }

    error_page 500 502 503 504 /500.html;
    location = /500.html {
      root /path/to/app/current/public;
    }
  }
}

para ver más acerca de esta configuración nginx.conf

En nuestro caso una configuración podria ser la siguiente: 

upstream hello_app_server {
  # fail_timeout=0 means we always retry an upstream even if it failed
  # to return a good HTTP response (in case the Unicorn master nukes a
  # single worker for timing out).

  server unix:/webapps/hello_django/run/gunicorn.sock fail_timeout=0;
}

server {

    listen   80;
    server_name example.com;

    client_max_body_size 4G;

    access_log /webapps/hello_django/logs/nginx-access.log;
    error_log /webapps/hello_django/logs/nginx-error.log;
 
    location /static/ {
        alias   /webapps/hello_django/static/;
    }
    
    location /media/ {
        alias   /webapps/hello_django/media/;
    }

    location / {
        # an HTTP header important enough to have its own Wikipedia entry:
        #   http://en.wikipedia.org/wiki/X-Forwarded-For
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        # enable this if and only if you use HTTPS, this helps Rack
        # set the proper protocol for doing redirects:
        # proxy_set_header X-Forwarded-Proto https;

        # pass the Host: header from the client right along so redirects
        # can be set properly within the Rack application
        proxy_set_header Host $http_host;

        # we don't want nginx trying to do something clever with
        # redirects, we set the Host: header above already.
        proxy_redirect off;

        # set "proxy_buffering off" *only* for Rainbows! when doing
        # Comet/long-poll stuff.  It's also safe to set if you're
        # using only serving fast clients with Unicorn + nginx.
        # Otherwise you _want_ nginx to buffer responses to slow
        # clients, really.
        # proxy_buffering off;

        # Try to serve static files from nginx, no point in making an
        # *application* server like Unicorn/Rainbows! serve static files.
        if (!-f $request_filename) {
            proxy_pass http://hello_app_server;
            break;
        }
    }

    # Error pages
    error_page 500 502 503 504 /500.html;
    location = /500.html {
        root /webapps/hello_django/static/;
    }
}

 

 Luego debemos crear un link simbolico a nuestra configuracion

sudo ln -s /etc/nginx/sites-available/myproject /etc/nginx/sites-enabled

Algunos comandos básicos para manejar nginx  son:

sudo nginx -t 
sudo systemctl restart nginx

Related Posts