GNU/Linux >> Tutoriales Linux >  >> Panels >> Docker

Una guía para principiantes de LXD:configuración de un proxy inverso para alojar varios sitios web

Introducción

LXD (pronunciado "Lex-Dee") es un administrador de contenedores del sistema construido sobre Linux Containers (LXC) compatible con Canonical. El objetivo de LXD es proporcionar una experiencia similar a una máquina virtual pero a través de contenedores en lugar de virtualización de hardware. En comparación con Docker para la entrega de aplicaciones, LXD ofrece una funcionalidad de sistema operativo casi completa con características adicionales como instantáneas, migraciones en vivo y administración de almacenamiento.

Un proxy inverso es un servidor que se encuentra entre las aplicaciones internas y los clientes externos, reenviando las solicitudes de los clientes al servidor apropiado. Si bien muchas aplicaciones comunes, como Node.js, pueden funcionar como servidores por sí mismas, es posible que carezcan de una serie de funciones avanzadas de equilibrio de carga, seguridad y aceleración.

Esta guía explica la creación de un proxy inverso en un contenedor LXD para alojar múltiples sitios web, cada uno en sus propios contenedores adicionales. Utilizará los servidores web NGINX y Apache, y también confiará en NGINX como proxy inverso.

Consulte el siguiente diagrama para comprender el proxy inverso creado en esta guía.

En esta guía usted:

  • Instale y configure contenedores para servidores web NGINX y Apache.

  • Aprenda a instalar y configurar un proxy inverso en un contenedor.

  • Obtenga soporte SSL/TLS a través de certificados Let's Encrypt con renovación automática de certificados.

  • Solución de problemas de errores comunes.

Nota Para simplificar, el término contenedor se usa a lo largo de esta guía para describir los contenedores del sistema LXD.

Antes de comenzar

  1. CompleteUna guía para principiantes de LXD:configuración de un servidor web Apache en un contenedor. La guía le indica que cree un contenedor llamado web con el servidor web Apache con fines de prueba. Elimina este contenedor ejecutando los siguientes comandos.

    lxc stop web
    lxc delete web
    
    Nota

    Para esta guía se necesita LXD versión 3.3 o posterior. Verifique la versión con el siguiente comando:

    lxd --version
    

    Si la versión no es 3.3 o posterior, actualice a la última versión instalando el paquete snap como se indica en Guía para principiantes de LXD:configuración de un servidor web Apache en un contenedor y use el siguiente comando:

    sudo lxd.migrate
    
  2. Esta guía utiliza los nombres de host apache1.example.com y nginx1.example.com para los dos sitios web de ejemplo. Reemplace estos nombres con nombres de host de su propiedad y configure sus entradas de DNS para que apunten a la dirección IP del servidor que creó. Para obtener ayuda con el DNS, consulte nuestra Guía del administrador de DNS.

Creando los Contenedores

  1. Crea dos contenedores llamados apache1 y nginx1 , uno con el servidor web Apache y otro con el servidor web NGINX, respectivamente. Para cualquier sitio web adicional, puede crear nuevos contenedores con el software de servidor web elegido.

    lxc launch ubuntu:18.04 apache1
    lxc launch ubuntu:18.04 nginx1
    
  2. Crea el proxy contenedor para el proxy inverso.

    lxc launch ubuntu:18.04 proxy
    
  3. Enumere los contenedores con el comando list.

    lxc list
    
  4. El resultado es similar al siguiente.

    +---------+---------+---------------------+-----------------------------------------------+------------+-----------+
    |  NAME   |  STATE  |        IPV4         |                     IPV6                      |    TYPE    | SNAPSHOTS |
    +---------+---------+---------------------+-----------------------------------------------+------------+-----------+
    | apache1 | RUNNING | 10.10.10.204 (eth0) | fd42:67a4:b462:6ae2:216:3eff:fe01:1a4e (eth0) | PERSISTENT |           |
    +---------+---------+---------------------+-----------------------------------------------+------------+-----------+
    | nginx1  | RUNNING | 10.10.10.251 (eth0) | fd42:67a4:b462:6ae2:216:3eff:febd:67e3 (eth0) | PERSISTENT |           |
    +---------+---------+---------------------+-----------------------------------------------+------------+-----------+
    | proxy   | RUNNING | 10.10.10.28 (eth0)  | fd42:67a4:b462:6ae2:216:3eff:fe00:252e (eth0) | PERSISTENT |           |
    +---------+---------+---------------------+-----------------------------------------------+------------+-----------+

    Hay tres contenedores, todos en el EN FUNCIONAMIENTO estado:cada uno con su propia dirección IP privada. Tome nota de las direcciones IP (tanto IPv4 como IPv6) para el contenedor proxy . Los necesitará para configurar el proxy contenedor en una sección posterior.

    Ahora que se han creado los contenedores, los siguientes pasos detallarán cómo configurar el software del servidor web en el apache1 y nginx1 contenedores y el proxy contenedor para que los servidores web sean accesibles desde Internet.

Configuración del contenedor del servidor web Apache

Cuando se utiliza un proxy inverso frente a un servidor web, el servidor web no conoce las direcciones IP de los visitantes. El servidor web solo ve la dirección IP del proxy inverso. Sin embargo, cada servidor web tiene una forma de identificar la dirección IP remota real de un visitante. Para Apache, esto se realiza con el módulo Remote IP Apache. Para que el módulo funcione, el proxy inverso debe estar configurado para pasar la información de la dirección IP remota.

  1. Inicie un shell en el apache1 contenedor.

    lxc exec apache1 -- sudo --user ubuntu --login
    
  2. Actualice la lista de paquetes en apache1 contenedor.

    sudo apt update
    
  3. Instale el paquete apache2 en el contenedor.

    sudo apt install -y apache2
    
  4. Cree el archivo /etc/apache2/conf-available/remoteip.conf .

    Archivo:remoteip .conf

    Puedes usar el nano editor de texto ejecutando el comando sudo nano /etc/apache2/conf-available/remoteip.conf . Tenga en cuenta que estas son las direcciones IP del proxy contenedor mostrado anteriormente, tanto para IPv4 como para IPv6. Reemplácelos con las direcciones IP de su lxc list salida.

    Nota En lugar de especificar las direcciones IP, también puede usar el nombre de host proxy.lxd . Sin embargo, el módulo RemoteIP Apache es peculiar cuando usa el nombre de host y usa solo una de las dos direcciones IP (ya sea IPv4 o IPv6), lo que significa que el servidor web Apache no conoce la dirección IP de origen real para algunas conexiones. Al enumerar explícitamente las direcciones IPv4 e IPv6, puede estar seguro de que RemoteIP acepta con éxito la información de IP de origen de todas las conexiones del proxy inverso.
  5. Habilite el nuevo remoteip.conf configuración.

     sudo a2enconf remoteip
    
    Enabling conf remoteip.
    To activate the new configuration, you need to run:
    systemctl reload apache2
  6. Habilitar la remoteip Módulo Apache.

     sudo a2enmod remoteip
    
    Enabling module remoteip.
    To activate the new configuration, you need to run:
    systemctl restart apache2
  7. Edite la página web predeterminada de Apache para hacer referencia a que se ejecuta dentro de un contenedor LXD.

     sudo nano /var/www/html/index.html
    

    Cambie la línea "¡Funciona!" (línea número 224) a "¡Funciona dentro de un contenedor LXD!" Guardar y salir.

  8. Reinicie el servidor web Apache.

     sudo systemctl reload apache2
    
  9. Vuelve al host.

     exit
    
  10. Ha creado y configurado el servidor web Apache, pero aún no se puede acceder al servidor desde Internet. Se vuelve accesible después de configurar el proxy contenedor en una sección posterior.

    Creación del contenedor del servidor web NGINX

    Al igual que Apache, NGINX no conoce las direcciones IP de los visitantes cuando usa un proxy inverso frente a un servidor web. En su lugar, solo ve la dirección IP del proxy inverso. Cada software de servidor web NGINX puede identificar la dirección IP remota real de un visitante con el módulo Real IP. Para que el módulo funcione, el proxy inverso debe configurarse en consecuencia para pasar la información sobre las direcciones IP remotas.

    1. Inicie un shell en el nginx1 contenedor.

      lxc exec nginx1 -- sudo --user ubuntu --login
      
    2. Actualice la lista de paquetes en nginx1 contenedor.

      sudo apt update
      
    3. Instalar NGINX en el contenedor.

      sudo apt install -y nginx
      
    4. Cree el archivo /etc/nginx/conf.d/real-ip.conf .

      Archivo:real -ip.conf
    1
    2
    
    RemoteIPHeader X-Real-IP
    RemoteIPTrustedProxy 10.10.10.28 fd42:67a4:b462:6ae2:216:3eff:fe00:252e

    Puedes usar el nano editor de texto ejecutando el comando sudo nano /etc/nginx/conf.d/real-ip.conf .

    Nota Ha especificado el nombre de host del proxy inverso, proxy.lxd . Cada contenedor LXD obtiene automáticamente un nombre de host, que es el nombre del contenedor más el sufijo .lxd . Especificando el set_real_ip_from campo con proxy.lxd , le indica al servidor web NGINX que acepte la información de la dirección IP real para cada conexión, siempre que esa conexión se origine en proxy.lxd . La información de la dirección IP real se encuentra en el encabezado HTTP X-Real-IP en cada conexión.
  11. Edite la página web predeterminada de NGINX para hacer una referencia de que se ejecuta dentro de un contenedor LXD.

     sudo nano /var/www/html/index.nginx-debian.html
    

    Cambie la línea "¡Bienvenido a nginx!" (línea número 14) a "¡Bienvenido a nginx ejecutándose en un contenedor del sistema LXD!". Guardar y salir.

  12. Reinicie el servidor web NGINX.

     sudo systemctl reload nginx
    
  13. Vuelve al host.

     exit
    
  14. Ha creado y configurado el servidor web NGINX, pero aún no se puede acceder al servidor desde Internet. Se vuelve accesible después de configurar el proxy contenedor en la siguiente sección.

    Configuración del proxy inverso

    En esta sección configurarás el contenedor proxy . Instalará NGINX y lo configurará como un proxy inverso, luego agregará el dispositivo proxy LXD apropiado para exponer los puertos 80 y 443 a Internet.

    1. Añadir dispositivos proxy LXD para redirigir las conexiones de Internet a los puertos 80 (HTTP) y 443 (HTTPS) en el servidor a los respectivos puertos en el proxy contenedor.

       lxc config device add proxy myport80 proxy listen=tcp:0.0.0.0:80 connect=tcp:127.0.0.1:80 proxy_protocol=true
       lxc config device add proxy myport443 proxy listen=tcp:0.0.0.0:443 connect=tcp:127.0.0.1:443 proxy_protocol=true
      
      Device myport80 added to proxy
      Device myport443 added to proxy

      El lxc config device add comando toma como argumentos:

    1
    2
    
    real_ip_header    X-Real-IP;
    set_real_ip_from  proxy.lxd;
    Nota

    Si desea eliminar un dispositivo proxy, use lxc config device remove . Si desea eliminar el dispositivo anterior myport80 , ejecute el siguiente comando:

    lxc config device remove proxy myport80
    

    Donde proxy es el nombre del contenedor y myport80 es el nombre del dispositivo.

  15. Inicie un shell en el proxy contenedor.

    lxc exec proxy -- sudo --user ubuntu --login
    
  16. Actualice la lista de paquetes.

    sudo apt update
    
  17. Instale NGINX en el contenedor.

    sudo apt install -y nginx
    
  18. Salga del contenedor.

    logout
    
  19. Tráfico directo al servidor web Apache desde el proxy inverso

    El contenedor de proxy inverso se está ejecutando y el paquete NGINX se ha instalado. Para trabajar como un proxy inverso, agregue la configuración de sitio web adecuada para que NGINX pueda identificar (con server_name a continuación) el nombre de host apropiado y luego pase (con proxy_pass a continuación) la conexión al contenedor LXD apropiado.

    1. Inicie un shell en el proxy contenedor.

      lxc exec proxy -- sudo --user ubuntu --login
      
    2. Crea el archivo apache1.example.com en /etc/nginx/sites-available/ para la configuración de su primer sitio web.

      Archivo:apache1 .ejemplo.com
    Argumento Explicación
    proxy El nombre del contenedor.
    myport80 Un nombre para este dispositivo proxy.
    proxy El tipo de dispositivo LXD (LXD proxy dispositivo).
    listen=tcp:0.0.0.0:80 El dispositivo proxy escucha en el host (predeterminado) en el puerto 80, protocolo TCP, en todas las interfaces.
    connect=tcp:127.0.0.1:80 El dispositivo proxy se conecta al contenedor en el puerto 80, protocolo TCP, en la interfaz loopback. En versiones anteriores de LXD, podría haber especificado localhost aquí. Sin embargo, en LXD 3.13 o posterior, solo puede especificar direcciones IP.
    proxy_protocol=true Solicite habilitar el protocolo PROXY para que el proxy inverso obtenga la dirección IP de origen del dispositivo proxy.

    Puede ejecutar sudo nano /etc/nginx/sites-available/apache1.example.com para abrir un editor de texto y agregar la configuración. Tenga en cuenta que, en este caso, solo necesita editar el server_name ser el nombre de host del sitio web.

  20. Habilitar el sitio web.

    sudo ln -s /etc/nginx/sites-available/apache1.example.com /etc/nginx/sites-enabled/
    
  21. Reinicie el proxy inverso NGINX. Al reiniciar el servicio, NGINX lee y aplica las instrucciones del nuevo sitio recién agregadas a /etc/nginx/sites-enabled .

    sudo systemctl reload nginx
    
  22. Salga del contenedor de proxy y regrese al host.

    logout
    
  23. Desde su computadora local, visite la URL de su sitio web con su navegador web. Debería ver la página predeterminada de Apache:

    Nota Si observa el archivo Apache access.log (archivo predeterminado /var/log/apache2/access.log ), todavía muestra la dirección IP privada del proxy contenedor en lugar de la dirección IP real. Este problema es específico del servidor web Apache y tiene que ver con la forma en que el servidor imprime los registros. Otro software en el servidor web puede usar la IP real. Para solucionar esto a través de los registros de Apache, consulte la sección Solución de problemas.
  24. Tráfico directo al servidor web NGINX desde el proxy inverso

    El contenedor de proxy inverso se está ejecutando y NGINX el paquete ha sido instalado. Para trabajar como un proxy inverso, debe agregar la configuración de sitio web adecuada para que NGINX puede identificar (con server_name a continuación) el nombre de host apropiado y luego pase (con proxy_pass a continuación) la conexión al contenedor LXD apropiado con el software del servidor web real.

    1. Inicie un shell en el proxy contenedor.

      lxc exec proxy -- sudo --user ubuntu --login
      
    2. Cree el archivo nginx1.example.com en /etc/nginx/sites-available/ para la configuración de su segundo sitio web.

      Archivo:nginx1 .ejemplo.com
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    
    server {
            listen 80 proxy_protocol;
            listen [::]:80 proxy_protocol;
    
            server_name apache1.example.com;
    
            location / {
                    include /etc/nginx/proxy_params;
    
                    proxy_pass http://apache1.lxd;
            }
    
            real_ip_header proxy_protocol;
            set_real_ip_from 127.0.0.1;
    }

    Puede ejecutar sudo nano /etc/nginx/sites-available/nginx1.example.com para crear la configuración. Tenga en cuenta que solo necesita editar los campos server_name ser el nombre de host del sitio web.

  25. Habilitar el sitio web.

    sudo ln -s /etc/nginx/sites-available/nginx1.example.com /etc/nginx/sites-enabled/
    
  26. Reinicie el servicio de proxy inverso NGINX.

    sudo systemctl reload nginx
    
  27. Salga del contenedor de proxy y regrese al host.

    logout
    
  28. Desde su computadora local, visite la URL de su sitio web con su navegador web. Debería ver la siguiente página NGINX predeterminada.

  29. Agregar soporte para HTTPS con Let's Encrypt

    1. Inicie un shell en el proxy contenedor.

      lxc exec proxy -- sudo --user ubuntu --login
      
    2. Agregue el repositorio ppa:certbot/certbot ejecutando el siguiente comando.

      sudo add-apt-repository ppa:certbot/certbot
      
    3. El resultado es similar al siguiente.

      This is the PPA for packages prepared by Debian Let's Encrypt Team and backported for Ubuntu(s).
            More info: https://launchpad.net/~certbot/+archive/ubuntu/certbot
           Press [ENTER] to continue or Ctrl-c to cancel adding it.
      
           Get:1 http://security.ubuntu.com/ubuntu bionic-security InRelease [88.7 kB]
           ...
           Fetched 3360 kB in 2s (2018 kB/s)
           Reading package lists... Done

    4. Instale los siguientes dos paquetes para a) respaldar la creación de certificados Let's Encrypt; yb) configurar automáticamente el proxy inverso NGINX para usar certificados de Let's Encrypt. Los paquetes se extraen del repositorio recién creado.

      sudo apt-get install certbot python-certbot-nginx
      
      Nota Esto configura el proxy inverso para que también actúe como un proxy de terminación de TLS . Cualquier configuración de HTTPS solo se encuentra en el proxy envase. Al hacerlo, no es necesario realizar ninguna tarea dentro de los contenedores del servidor web en relación con los certificados y Let's Encrypt.
    5. Ejecute certbot como root con --nginx parámetro para realizar la configuración automática de Let's Encrypt para el primer sitio web. Se le solicita que proporcione una dirección de correo electrónico válida para la renovación urgente y los avisos de seguridad. Luego se le pide que acepte los Términos de servicio y si desea que Electronic Frontier Foundation se comunique con usted en el futuro. A continuación, proporcione el sitio web para el que está activando HTTPS. Finalmente, puede optar por configurar una instalación que redirija automáticamente las conexiones HTTP a las conexiones HTTPS.

      sudo certbot --nginx
      
      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.2-November-15-2017.pdf. You must
      agree in order to register with the ACME server at
      https://acme-v02.api.letsencrypt.org/directory
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      (A)gree/(C)ancel: A
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Would you be willing 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: N
      
      Which names would you like to activate HTTPS for?
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      1: apache1.example.com
      2: nginx1.example.com
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Select the appropriate numbers separated by commas and/or spaces, or leave input
      blank to select all options shown (Enter 'c' to cancel): 1
      Obtaining a new certificate
      Performing the following challenges:
      http-01 challenge for apache1.example.com
      Waiting for verification...
      Cleaning up challenges
      Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/apache1.example.com
      
      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      1: No redirect - Make no further changes to the webserver configuration.
      2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
      new sites, or if you're confident your site works on HTTPS. You can undo this
      change by editing your web server's configuration.
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
      Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/apache1.example.com
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Congratulations! You have successfully enabled https://apache1.example.com
      
      You should test your configuration at:
      https://www.ssllabs.com/ssltest/analyze.html?d=apache1.example.com
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      
      IMPORTANT NOTES:
       - Congratulations! Your certificate and chain have been saved at:
         /etc/letsencrypt/live/apache1.example.com/fullchain.pem
         Your key file has been saved at:
         /etc/letsencrypt/live/apache1.example.com/privkey.pem
         Your cert will expire on 2019-10-07. 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"
       - Your account credentials have been saved in your Certbot
         configuration directory at /etc/letsencrypt. You should make a
         secure backup of this folder now. This configuration directory will
         also contain certificates and private keys obtained by Certbot so
         making regular backups of this folder is ideal.
       - 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
    6. Ejecute certbot como root con --nginx parámetro para realizar la configuración automática de Let's Encrypt para el segundo sitio web. Esta es la segunda vez que ejecutamos certbot , por lo que se nos pide directamente que seleccionemos el sitio web a configurar.

      sudo certbot --nginx
      
      Saving debug log to /var/log/letsencrypt/letsencrypt.log
      Plugins selected: Authenticator nginx, Installer nginx
      
      Which names would you like to activate HTTPS for?
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      1: apache1.example.com
      2: nginx1.example.com
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Select the appropriate numbers separated by commas and/or spaces, or leave input
      blank to select all options shown (Enter 'c' to cancel): 2
      Obtaining a new certificate
      Performing the following challenges:
      http-01 challenge for nginx1.example.com
      Waiting for verification...
      Cleaning up challenges
      Deploying Certificate to VirtualHost /etc/nginx/sites-enabled/nginx1.example.com
      
      Please choose whether or not to redirect HTTP traffic to HTTPS, removing HTTP access.
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      1: No redirect - Make no further changes to the webserver configuration.
      2: Redirect - Make all requests redirect to secure HTTPS access. Choose this for
      new sites, or if you're confident your site works on HTTPS. You can undo this
      change by editing your web server's configuration.
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Select the appropriate number [1-2] then [enter] (press 'c' to cancel): 2
      Redirecting all traffic on port 80 to ssl in /etc/nginx/sites-enabled/nginx1.example.com
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Congratulations! You have successfully enabled https://nginx1.example.com
      
      You should test your configuration at:
      https://www.ssllabs.com/ssltest/analyze.html?d=nginx1.example.com
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      
      IMPORTANT NOTES:
       - Congratulations! Your certificate and chain have been saved at:
         /etc/letsencrypt/live/nginx1.example.com/fullchain.pem
         Your key file has been saved at:
         /etc/letsencrypt/live/nginx1.example.com/privkey.pem
         Your cert will expire on 2019-10-07. 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
    7. Después de agregar todos los sitios web, realice un simulacro para probar la renovación de los certificados. Verifique que todos los sitios web se actualicen correctamente para garantizar que la instalación automatizada actualice los certificados sin más esfuerzo.

      sudo certbot renew --dry-run
      
      Saving debug log to /var/log/letsencrypt/letsencrypt.log
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Processing /etc/letsencrypt/renewal/apache1.example.com.conf
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Cert not due for renewal, but simulating renewal for dry run
      Plugins selected: Authenticator nginx, Installer nginx
      Renewing an existing certificate
      Performing the following challenges:
      http-01 challenge for apache1.example.com
      Waiting for verification...
      Cleaning up challenges
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      new certificate deployed with reload of nginx server; fullchain is
      /etc/letsencrypt/live/apache1.example.com/fullchain.pem
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Processing /etc/letsencrypt/renewal/nginx1.example.com.conf
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      Cert not due for renewal, but simulating renewal for dry run
      Plugins selected: Authenticator nginx, Installer nginx
      Renewing an existing certificate
      Performing the following challenges:
      http-01 challenge for nginx1.example.com
      Waiting for verification...
      Cleaning up challenges
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      new certificate deployed with reload of nginx server; fullchain is
      /etc/letsencrypt/live/nginx1.example.com/fullchain.pem
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      ** DRY RUN: simulating 'certbot renew' close to cert expiry
      **          (The test certificates below have not been saved.)
      
      Congratulations, all renewals succeeded. The following certs have been renewed:
        /etc/letsencrypt/live/apache1.example.com/fullchain.pem (success)
        /etc/letsencrypt/live/nginx1.example.com/fullchain.pem (success)
      ** DRY RUN: simulating 'certbot renew' close to cert expiry
      **          (The test certificates above have not been saved.)
      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
      
      IMPORTANT NOTES:
       - Your account credentials have been saved in your Certbot
         configuration directory at /etc/letsencrypt. You should make a
         secure backup of this folder now. This configuration directory will
         also contain certificates and private keys obtained by Certbot so
         making regular backups of this folder is ideal.
      Nota El certbot el paquete agrega un temporizador systemd para activar la renovación automática de los certificados de Let’s Encrypt. Puede ver los detalles de este temporizador ejecutando systemctl list-timers .
    8. La herramienta certbot edita y cambia los archivos de configuración NGINX de sus sitios web. Al hacerlo, certbot no obedece el listen inicial directiva (listen 80 proxy_protocol; ) y no agrega el proxy_protocol parámetro al listen 443 ssl; recién agregado líneas. Debe editar los archivos de configuración para cada sitio web y agregar "proxy_protocol" a cada "listen 443 ssl"; línea.

       sudo nano /etc/nginx/sites-enabled/apache1.example.com
       sudo nano /etc/nginx/sites-enabled/nginx1.example.com
      
      listen 443 ssl proxy_protocol; # managed by Certbot
      listen [::]:443 ssl proxy_protocol; # managed by Certbot
      Nota Cada archivo de configuración del sitio web tiene dos pares de listen directivas:HTTP y HTTPS, respectivamente. El primero es el par original para HTTP que se agregó en una sección anterior. El segundo par fue agregado por certbot para HTTPS. Estos son pares porque cubren tanto IPv4 como IPv6. La notación [::] se refiere a IPv6. Al agregar el parámetro proxy_protocol , añádelo antes del ; en cada línea como se muestra arriba.
    9. Reinicie NGINX.

      sudo systemctl restart nginx
      

    Solución de problemas

    Browser Error “SSL_ERROR_RX_RECORD_TOO_LONG”

    You have configured Certbot and created the appropriate Let’s Encrypt configuration for each website. But when you access the website from your browser, you get the following error.

    Secure Connection Failed
    
    An error occurred during a connection to apache1.example.com. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG
    
        The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
        Please contact the website owners to inform them of this problem.

    This error is caused when the NGINX reverse proxy in the proxy container does not have the proxy_protocol parameter in the listen 443 directives. Without the parameter, the reverse proxy does not consume the PROXY protocol information before it performs the HTTPS work. It mistakenly passes the PROXY protocol information to the HTTPS module, hence the record too long error.

    Follow the instructions in the previous section and add proxy_protocol to all listen 443 directives. Finally, restart NGINX.

    Error “Unable to connect” or “This site can’t be reached”

    When you attempt to connect to the website from your local computer and receive Unable to connect or This site can’t be reached errors, it is likely the proxy devices have not been configured.

    Run the following command on the host to verify whether LXD is listening and is able to accept connections to ports 80 (HTTP) and 443 (HTTPS).

    sudo ss -ltp '( sport = :http || sport = :https )'
    
    Nota

    The ss command is similar to netstat and lsof . It shows information about network connections. In this case, we use it to verify whether there is a service on ports 80 and 443, and which service it is.

    • -l , to display the listening sockets,
    • -t , to display only TCP sockets,
    • -p , to show which processes use those sockets,
    • ( sport = :http || sport = :https ) , to show only ports 80 and 443 (HTTP and HTTPS, respectively).

    In the following output we can verify that both ports 80 and 443 (HTTP and HTTPS, respectively) are in the LISTEN Expresar. In the last column we verify that the process listening is lxd itself.

    State     Recv-Q  Send-Q   Local Address:Port   Peer Address:Port
    LISTEN    0       128                  *:http              *:*       users:(("lxd",pid=1301,fd=7),("lxd",pid=1301,fd=5))
    LISTEN    0       128                  *:https             *:*       users:(("lxd",pid=1349,fd=7),("lxd",pid=1349,fd=5))

    If you see a process listed other than lxd , stop that service and restart the proxy envase. By restarting the proxy container, LXD applies the proxy devices again.

    The Apache access.log Shows the IP Address of the Proxy Container

    You have set up the apache1 container and verified that it is accessible from the internet. But the logs at /var/log/apache2/access.log still show the private IP address of the proxy container, either the private IPv4 (10.x.x.x ) or the private IPv6 addresses. What went wrong?

    The default log formats for printing access logs in Apache only print the IP address of the host of the last hop (i.e. the proxy server). This is the %h format specifier as shown below.

    LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
    LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %O" common

    The %h must be manually replaced with the %a format specifier, which prints the value as returned by the real RemoteIP Apache module.

    LogFormat "%v:%p %a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
    LogFormat "%a %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%a %l %u %t \"%r\" %>s %O" common
    1. Run the following command in the apache1 container to edit the configuration file httpd.conf and perform the change from %h to %a .

      sudo nano /etc/apache2/apache2.conf
      
    2. Reload the Apache web server service.

       sudo systemctl reload apache2
      

    Next Steps

    You have set up a reverse proxy to host many websites on the same server and installed each website in a separate container. You can install static or dynamic websites in the containers. For dynamic websites, you may need additional configuration; check the respective documentation for setup using a reverse proxy. In addition, you may also use NGINX as a reverse proxy for non-HTTP(S) services.

    Más información

    Es posible que desee consultar los siguientes recursos para obtener información adicional sobre este tema. Si bien estos se proporcionan con la esperanza de que sean útiles, tenga en cuenta que no podemos garantizar la precisión o la puntualidad de los materiales alojados externamente.

    • LXD Introduction
    • LXD support community
    • Try LXD Online
    • NGINX Web Server
    • Apache Web Server
    • NGINX Reverse Proxy Settings
    • Proxy Protocol
    • TLS Termination Proxy

    Docker
    1. Cómo configurar un proxy inverso Nginx

    2. Aloja varios sitios web en contenedores Docker

    3. Configurar Nginx como proxy inverso en Ubuntu 20.04 - ¿Guía paso a paso?

    4. Una guía para principiantes de LXD:configuración de un servidor web Apache

    5. Guía para principiantes de rutas múltiples de Device Mapper (DM)

    Una guía para principiantes de LVM

    Configurar una IP estática en Ubuntu:una guía para principiantes

    Una guía para principiantes sobre los trabajos de Cron

    Cómo configurar el proxy inverso de Nginx

    Guía para principiantes del mundo Docker

    Guía para principiantes de gestión de usuarios de MySQL

       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      
      server {
              listen 80 proxy_protocol;
              listen [::]:80 proxy_protocol;
      
              server_name nginx1.example.com;
      
              location / {
                      include /etc/nginx/proxy_params;
      
                      proxy_pass http://nginx1.lxd;
              }
      
              real_ip_header proxy_protocol;
              set_real_ip_from 127.0.0.1;
      }