Instalación
=====================================

.. toctree::
   :maxdepth: 2

.. note:: Django en producción con Gunicorn y Nginx.

    Se crea un socket 'unix' para la comunicación entre la aplicación y el gunicorn.

    Nginx se ocupa de distribuir los ficheros estáticos de la aplicación y las peticiones al gunicorn.


Esquema
#######

.. figure:: /_static/img/nginx-django.webp

Crear socket unix
#################

**Fichero /etc/systemd/system/gunicorn.socket**

.. code-block::
    :linenos:

    [Unit]
    Description=gunicorn socket

    [Socket]
    ListenStream=/run/gunicorn.sock
    SocketUser=diego

    [Install]
    WantedBy=sockets.target

**Iniciar el socket gunicorn.socket**

.. code-block::
    :linenos:

    systemctl enable gunicorn.socket
    systemctl start gunicorn.socket


Crear servicio gunicorn
#######################

**Fichero /etc/systemd/system/gunicorn.service**

.. code-block:: bash
    :linenos:

    [Unit]
    Description=gunicorn daemon
    Requires=gunicorn.socket
    After=network.target

    [Service]
    User=diego
    Group=diego
    WorkingDirectory=/opt/django
    ExecStart=/opt/django/.venv/bin/gunicorn \--bind unix:/run/gunicorn.sock -w 3 encuestas.wsgi
    TimeoutStopSec=5
    PrivateTmp=true

    [Install]
    WantedBy=multi-user.target

**Iniciar el socket gunicorn.service**

.. code-block::
    :linenos:

    systemctl enable gunicorn.service
    systemctl start gunicorn.service

Configurar la aplicación
########################

**Fichero /opt/django/encuestas/setting.py**

.. code-block::
    :linenos:

    STATIC_URL = 'static/'
    STATIC_ROOT = os.path.join(BASE_DIR, 'static')
    STATICFILES_DIRS = [
            '/opt/django/helloworld/static/', os.path.join(BASE_DIR,'static/')
     ]

Configurar nginx
########################

**Fichero /etc/nginx/nginx.conf**

.. code-block::
    :linenos:

        server {
              listen 80;
              server_name _default;
              location ^~ /django/static {
                root /opt;
              }
              location ^~ /django {
                proxy_pass http://unix:/run/gunicorn.sock;
              }
