Absortio

Email → Summary → Bookmark → Email

Raspberry Pi, Static HTTPS site with Docker and Nginx

Extracto

Raspberry Pi, Static HTTPS site with Docker and Nginx - Raspberry Pi, Static HTTPS site with Docker and Nginx.md

Resumen

Resumen Principal

El tutorial detalla el proceso de configuración de un sitio web estático con HTTPS utilizando Docker y Nginx en una Raspberry Pi, combinando tecnologías modernas de contenedores con hardware accesible para crear una solución de hosting ligera y segura. El enfoque se centra en la orquestación de contenedores Docker para ejecutar Nginx como servidor web y en la implementación de certificados SSL/TLS mediante Let's Encrypt, garantizando una capa de seguridad esencial para sitios accesibles desde internet. La guía aborda aspectos como la configuración inicial del entorno Docker, la creación de volúmenes persistentes para almacenamiento de datos y certificados, y la definición de archivos de configuración personalizados para Nginx. Además, se incluye la automatización del proceso de renovación de certificados, asegurando que el sitio mantenga su conexión segura sin intervención manual. Este enfoque permite transformar una Raspberry Pi en un servidor web seguro y eficiente, aprovechando las ventajas de la virtualización ligera y la automatización de tareas críticas como la gestión de certificados.

Elementos Clave

  • Configuración de Docker en Raspberry Pi: El tutorial comienza con la preparación del entorno Docker, incluyendo la instalación del motor de contenedores y la creación de redes personalizadas para aislar el tráfico del sitio web, lo que mejora la seguridad y el control del despliegue.
  • Implementación de Nginx como servidor web: Se detalla la configuración de Nginx mediante archivos de configuración personalizados montados como volúmenes, permitiendo servir contenido estático optimizado y gestionar múltiples dominios desde una única instancia del contenedor.
  • Integración con Let's Encrypt para HTTPS: Se implementa un sistema automatizado para obtener y renovar certificados SSL/TLS utilizando el protocolo ACME, asegurando que el sitio web cumpla con los estándares de seguridad modernos y sea reconocido como confiable por los navegadores.
  • Gestión de volúmenes persistentes: Se configuran volúmenes Docker dedicados para almacenar tanto los archivos del sitio web como los certificados SSL, garantizando que los datos permanezcan disponibles incluso después de reiniciar o actualizar los contenedores.

Análisis e Implicaciones

Esta solución representa una alternativa económica y educativa para el despliegue de sitios web seguros, aprovechando hardware de bajo costo como la Raspberry Pi para ejecutar tecnologías empresariales como Docker y HTTPS. La combinación de contenedores ligeros con certificados SSL gratuitos democratiza el acceso a prácticas de hosting profesional, permitiendo a desarrolladores y entusiastas implementar infraestructura web segura sin costos elevados. Además, el enfoque en la automatización de la renovación de certificados establece un modelo sostenible para el mantenimiento a largo plazo de sitios web personales o proyectos educativos.

Contexto Adicional

El uso de Raspberry Pi como plataforma de servidor web ha ganado popularidad gracias a su bajo consumo energético y su capacidad para ejecutar sistemas Linux completos, convirtiéndola en una opción ideal para proyectos de aprendizaje y prototipado. La implementación de Docker en este contexto permite replicar fácilmente el entorno de producción en otros dispositivos compatibles, facilitando el despliegue y la escalabilidad de aplicaciones web estáticas con requisitos mínimos de infraestructura.

Contenido

Raspberry Pi, Static HTTPS site with Docker and Nginx

This tutorial is dated Oct 2021, if it's much further on than that this information might be out of date.

This is a guide on setting up a static HTTPS website on your raspberry pi using docker and nginx. The aim is to have this running on the raspberry pi and to be able to access it from a host computer on the same local network. You should already be able to ssh into your pi from your host computer and have raspberry pi OS set up.

Find your raspberry pi

If you dont know how to reach your raspberry pi you can run this command as root on your host to find all available devices

host# grc nmap -sn -T aggressive 192.168.1.0/24

The /24 means to scan all the ip addresses of the form 192.168.1.*.

Set up Docker

Install docker (# means as root) and add your regular user to the docker group:

pi# apt install docker docker-compose
pi# systemctl enable docker
pi# usermod -aG docker pi

Reboot and ensure that you can run docker hello world:

pi$ docker run hello-world

Run a prepared static website in docker

Try to run this test webserver and then access it from a web browser on your host machine:

pi$ docker run -d -p 80:80 hypriot/rpi-busybox-httpd

I've named my device rpi in its /etc/hostname file, which means I can access it via ssh as pi@rpi.lan instead of using an ip address. By default it was called raspberrypi but I wanted to shorten it. This means I will also be able to access it in a web browser as http://rpi.lan/ This feature (The ability to refer to the device from your host using a name rather than ip address) is implemented by mDNS. An alternative to this is to add an entry to your /etc/hosts file on your host machine.

Run a custom static site with nginx

Make a directory on your pi for this project. I called it docker-nginx-test. Make a directory on your pi called html/ and put at least some index.html file in it. Create the following Dockerfile:

FROM nginx
COPY html /usr/share/nginx/html

This creates a docker image based off the nginx image with your own change of copying in your custom html. Ensure you can build and run this, and access it from your host machine.

pi$ docker build -t docker-nginx-test .
pi$ docker run -p 80:80 docker-nginx-test

Creating an OpenSSL CA to add to your browser

The omgwtfssl docker image saved me a lot of trouble messing around with openssl command line tools. It's a run once to generate the files kind of thing. Create a directory for your CA and certs. If you rerun the command with different options it will reuse the existing CA (nice feature!).

host$ mkdir certs
host$ docker run --mount type=bind,source=`pwd`/certs,target=/certs -e SSL_SUBJECT="rpi.lan" -e SSL_DNS="rpi.lan" paulczar/omgwtfssl

Now if you go into Chromium browser settings and search "certificates", in the Security tab, Manage Certificates, you can add an Authority. Import 'ca.pem'. Tell the browser to Trust this certificate for identifying websites. This should add 'org-test-ca' to your browser. This allows HTTPS certificates signed by that to be seen as valid in your browser.

Run a custom nginx configuration

Before setting up TLS we want to edit the nginx configuration. This is a little bit easier if you don't use docker. It might be useful to have practiced with configuring and setting up a server before doing so in docker, just because docker abstracts you away from it by one level. This also brings advantages which is why we are bothering to use docker. Anyway, following the guidance from the docker hub page for nginx:

copy the entire /etc/nginx configuration folder out of the stock docker image so that we can edit it and copy it into our custom image. The file we want to edit is nginx/conf.d/default.conf. For now just add a comment like ### I EDITED THIS FILE! to the end of this file. This will let us to verify that our changed version was put into the docker image we're about to create. I messed this up before and I was having HTTPS not working, but no errors about why it wasn't working. So it can save time if you are check things like this.

New Dockerfile:

FROM nginx
COPY html /usr/share/nginx/html
COPY nginx /etc/nginx/

Now build the docker container and you can execute a bash shell inside it, to look around and check that the config file has been edited.

pi$ docker build -t docker-nginx-https-test .
pi$ docker run -t docker-nginx-https-test -i bash
root@c334b184bede:/# cat /etc/nginx/conf.d/default.conf

Setting up HTTPS

Tip: You can run netstat -tulpn on your pi to see what ports it is listening on.

Add the following lines to your nginx config

    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    ssl_certificate /etc/nginx/ssl/cert.pem;
    ssl_certificate_key /etc/nginx/ssl/key.pem;

as well as creating an ssl/ directory inside your nginx config folder.

and copy those two files (cert.pem and key.pem) from your host into nginx/ssl/ on your pi.

You can build this docker image as before, to run it you need to provide the ssl port, so:

docker run -p 80:80 -p 443:443 docker-nginx-https-test

You should have a working static HTTPS website on your pi now!

Big thanks to Ristovski for the tip to use omgwtfssl!

Fuente: Gist