Automatización de HTTPS con Docker, Nginx y Certbot

Guía para automatizar TLS con Lets Encrypt mediante Docker, Nginx y Certbot: despliegue reproducible de HTTPS y renovaciones automáticas con proxy inverso.

1 sept 2025 • 4 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

El tráfico web seguro con HTTPS ya no es opcional, es lo esperado. En esta guía aprenderás a automatizar la emisión y renovación de certificados TLS de Lets Encrypt utilizando Docker, Nginx y Certbot, empaquetado para que el despliegue sea repetible y de bajo mantenimiento. Público objetivo: desarrolladores y equipos de operaciones con experiencia básica en Docker y comandos de Linux.

Qué lograrás: desplegar Nginx como proxy inverso en Docker, obtener y renovar automáticamente certificados TLS de Lets Encrypt con Certbot y mantener una configuración simple, reproducible y apta para producción.

Requisitos previos: Docker y Docker Compose instalados en un host con un dominio público apuntando a su IP, puertos 80 y 443 accesibles desde internet y familiaridad básica con la configuración de Nginx y Docker Compose.

Estructura del proyecto: crea un directorio con los siguientes elementos. Archivo docker-compose.yml. Carpeta nginx con subcarpeta conf.d y un archivo de configuración por sitio como default.conf. Carpeta certbot con subcarpeta www para los archivos del desafío HTTP. Carpeta data para el almacenamiento de certificados en etc letsencrypt.

Paso 1 — Docker Compose. Define dos servicios: nginx y certbot. Nginx expone los puertos 80 y 443, monta nginx conf.d en etc nginx conf.d en modo solo lectura, monta certbot www en var www certbot también en solo lectura y monta data en etc letsencrypt para persistir certificados. Certbot monta las mismas rutas y ejecuta de forma periódica la renovación con webroot sobre var www certbot y, al renovar, recarga Nginx para aplicar los nuevos certificados. Configura la política de reinicio en ambos servicios como unless-stopped.

Paso 2 — Nginx para desafíos ACME y proxy. Crea dos bloques de servidor. En el puerto 80 define server_name con tus dominios y publica la ruta .well-known acme-challenge desde var www certbot .well-known acme-challenge. Redirige el resto del tráfico a HTTPS con un 301 hacia https host request_uri. En el puerto 443 activa ssl y apunta ssl_certificate a etc letsencrypt live tu-dominio fullchain.pem y ssl_certificate_key a etc letsencrypt live tu-dominio privkey.pem. Endurece lo básico con protocolos TLSv1.2 y TLSv1.3 y, en location slash, define proxy_pass a tu aplicación upstream, además de las cabeceras Host y X-Real-IP.

Paso 3 — Emisión inicial del certificado. Antes de servir HTTPS, solicita los certificados con el plugin webroot ejecutando en el host: docker compose run --rm certbot certonly --webroot -w /var/www/certbot -d example.com -d www.example.com --email you@example.com --agree-tos --no-eff-email. Si es exitoso, encontrarás los certificados en data live example.com. Inicia o reinicia la pila con docker compose up -d.

Paso 4 — Validación y pruebas. Accede a https://example.com y verifica que el certificado sea válido y emitido por Lets Encrypt. Prueba la renovación en modo simulación con docker compose run --rm certbot renew --dry-run --webroot -w /var/www/certbot. Certbot gestionará renovaciones de forma automática en segundo plano.

Resolución de problemas. DNS: el dominio debe apuntar a la IP del host. Puertos: confirma que 80 y 443 estén abiertos y sin bloqueos de firewall o servicios en conflicto. Permisos: Nginx debe poder leer la ruta certbot www. Configuración: dentro del contenedor, valida la sintaxis con nginx -t. Logs: revisa los registros de Nginx y Certbot para identificar errores de desafío ACME y problemas de proxy.

Seguridad y operación. Almacena la carpeta data en disco cifrado si contiene claves sensibles. Supervisa la caducidad de certificados con alertas, ya que expiran cada 90 días. Para flujos avanzados, considera un cliente ACME con webhooks y notificaciones. En alta disponibilidad, centraliza la emisión de certificados en un único gestor y distribúyelos mediante sincronización segura.

Mejoras opcionales. Usa labels de Docker con un proxy dinámico como Traefik para automatizar routing y certificados. Activa HSTS, OCSP stapling y suites de cifrado robustas en Nginx acorde a tu política. Automatiza copias de seguridad con rotación de la carpeta data. Integra validaciones de infraestructura como código y tests de smoke tras cada renovación.

Cómo encaja esto con tu estrategia tecnológica. Automatizar HTTPS reduce tiempos de despliegue, elimina tareas manuales y mejora tu postura de ciberseguridad, especialmente si operas cargas en la nube. Si necesitas asesoría o implantación llave en mano, en Q2BSTUDIO te ayudamos a diseñar y operar plataformas seguras y escalables, alineadas con buenas prácticas de DevOps y FinOps.

Sobre Q2BSTUDIO. Somos una empresa de desarrollo con foco en aplicaciones a medida y software a medida, especialistas en inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA y power bi. Combinamos arquitectura cloud, automatización y observabilidad para acelerar tu tiempo a producción, reforzar el cumplimiento y mejorar la experiencia de tus usuarios. Descubre cómo fortalecemos tu seguridad con auditorías y pruebas de intrusión en nuestra página de ciberseguridad y pentesting, y cómo optimizamos tu infraestructura con servicios cloud en AWS y Azure. Si además buscas potenciar tus decisiones con datos y analítica, también diseñamos soluciones de servicios inteligencia de negocio y power bi integradas con tus sistemas.

Conclusión. Con Docker, Nginx y Certbot puedes estandarizar y automatizar HTTPS de forma fiable. Empieza por lo esencial, documenta tu pipeline, monitoriza renovaciones y evoluciona hacia un modelo centralizado si creces. Y si necesitas apoyo de un socio con experiencia en automatización de procesos, seguridad y nube, cuenta con Q2BSTUDIO.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat