Static Website in Docker with OpenTofu
Un solo tofu apply sirve tu sitio web estático desde nginx en Docker, con ajustes validados, una comprobación de estado, siete pruebas y un tofu destroy limpio.
- OpenTofu
- Docker provider (kreuzwerker/docker)
- HTTP provider (hashicorp/http)
- nginx (alpine image)
- Docker Desktop
Capturas de pantalla
Pago único
- 299 INR+ GST, 352,82 INR en total
- 5 US$
- Descárgalo desde tu biblioteca en cuanto se confirme tu pago.
- Incluye todas las versiones futuras de este proyecto, sin costo adicional.
- Última versión
- 1.0.0 · 18 nov 2026
- Licencia
- Source Code Licence
Descripción general
El código fuente completo de una configuración de OpenTofu que sirve una carpeta de archivos estáticos desde nginx en Docker, en tu propio equipo. Cada ajuste se comprueba antes de crear nada, el apply solo termina cuando nginx responde, una comprobación confirma que el sitio devuelve 200 y siete pruebas se ejecutan sin Docker. Probado en macOS con Docker Desktop.
Poner un sitio estático en un contenedor una vez es fácil. Hacerlo de modo que un ajuste incorrecto se detecte antes de que arranque nada, que el comando espere hasta que el sitio responda de verdad y que un solo comando lo quite todo de nuevo exige más cuidado. Static Website in Docker with OpenTofu® es esa configuración, probada en ejecuciones reales en macOS con Docker Desktop.
Qué hace
- Sirve tu sitio desde nginx en Docker. Indícale cualquier carpeta con un
index.htmly todos sus archivos, subcarpetas incluidas, se copian en un contenedor de nginx. - Un comando para levantarlo, otro para quitarlo.
tofu applydescarga la imagen oficialnginx:1.31-alpinee inicia el contenedor.tofu destroyelimina el contenedor y la imagen. - Privado de forma predeterminada. El sitio escucha en
127.0.0.1:8080, así que solo tu equipo puede abrirlo. Un solo ajuste lo abre a tu red. - Se actualiza cuando cambian tus archivos. Cambia un archivo y vuelve a ejecutar
tofu apply: el contenedor se sustituye por uno con los archivos nuevos.
Hecha para que los errores aparezcan pronto
- Cada ajuste se comprueba primero. El nombre del contenedor, la carpeta del sitio, el puerto (de 1024 a 65535), la dirección y la imagen se validan antes de crear nada, cada uno con un mensaje claro.
- El apply espera a que el sitio esté operativo. Una comprobación de estado dentro del contenedor pide a nginx la página de inicio, y
tofu applysolo termina cuando nginx responde. - Una comprobación tras cada apply. Un bloque
checkhace una petición al sitio y avisa si no responde con 200. - Siete pruebas.
tofu testcubre los valores predeterminados, la opción de red y todas las validaciones de entrada. Los proveedores están simulados, así que las pruebas no necesitan Docker ni crean nada.
Código sobre el que construir
- Pequeño y legible. Seis archivos
.tfcortos, cada uno con una sola tarea: las versiones, el proveedor, los ajustes, los recursos, la comprobación y las salidas. - Versiones fijadas y resultados reproducibles. Restricciones de versión para OpenTofu y los dos proveedores, y un archivo de bloqueo con sumas de comprobación para macOS (Apple silicon e Intel), Linux (x86-64 y Arm) y Windows.
- Listo para Git. Un
.gitignoreque deja fuera el estado y los planes, y.gitattributespara que los finales de línea sean coherentes. - Todos los ajustes en un archivo de ejemplo. Copia
terraform.tfvars.exampley cambia lo que necesites.
Lo que no incluye
- Sin alojamiento. Ejecuta el sitio en tu propio equipo. Llevarlo a un servidor o a la nube depende de ti.
- Sin HTTPS. nginx sirve solo HTTP en el puerto que elijas.
- Sin generador de sitios. Sirve los archivos que le des. El ejemplo es una tienda de una sola página.
Ponla en marcha en cuatro pasos
- Instala OpenTofu 1.13 o posterior e inicia Docker. En un Mac, activa el socket predeterminado de Docker Desktop o define
docker_host. - Descomprime la descarga y abre una terminal en su carpeta.
- Ejecuta
tofu init, despuéstofu apply, y escribeyes. - Abre
http://127.0.0.1:8080/en tu navegador.
Cada paso, con capturas de pantalla: How to Set Up and Run the Static Website in Docker with OpenTofu (se abre en una pestaña nueva) (en inglés).
Aprende las ideas que hay detrás del código en el tutorial gratuito OpenTofu Tutorial for Beginners (se abre en una pestaña nueva) (en inglés).
OpenTofu® es una marca registrada de LF Projects, LLC. Docker es una marca comercial de Docker, Inc. Los demás nombres son marcas comerciales de sus respectivos propietarios.
Serie de tutoriales gratuita
OpenTofu Tutorial for Beginners
¿Prefieres aprender construyéndolo? Esta guía gratuita y paso a paso en nuestro blog muestra cómo se hace el proyecto.
Qué te llevas
Todo lo que hay en el archivo, de un vistazo.
- La versión 1.0.0 del código fuente completo: seis archivos de OpenTofu, un sitio de ejemplo y un archivo de pruebas
- Ajustes validados para el nombre del contenedor, la carpeta del sitio, el puerto, la dirección y la imagen de nginx
- Un contenedor de nginx con comprobación de estado, y un apply que espera hasta que el sitio responde
- Un bloque check que confirma que el sitio responde con 200 después de cada apply
- Siete pruebas con proveedores simulados que se ejecutan sin Docker
- Un archivo de bloqueo con las sumas de comprobación de los proveedores para macOS, Linux y Windows
- Un archivo de ajustes de ejemplo, un .gitignore y un archivo .gitattributes
- Un README con los requisitos, todos los ajustes, las salidas, la solución de problemas y la limpieza
Construido con
Los entornos y las versiones exactos con los que se creó y se probó.
- OpenTofu1.13.9
- Docker provider (kreuzwerker/docker)4.7.0
- HTTP provider (hashicorp/http)3.6.3
- nginx (alpine image)1.31
- Docker Desktop4.99.0
Qué contiene el archivo
El árbol de carpetas que obtienes al descomprimirlo.
static-website-docker-opentofu/
- site/
- tests/
- .gitattributes
- .gitignore
- .terraform.lock.hcl
- README.md
- checks.tf
- main.tf
- outputs.tf
- providers.tf
- terraform.tfvars.example
- variables.tf
- versions.tf
Qué necesita de ti
Las cuentas y los servicios que espera encontrar, para que nada te sorprenda.
- OpenTofu 1.13 o posterior, anterior a la 2.0
- Docker: Docker Desktop en macOS o Windows, o Docker Engine en Linux
- En un Mac, el socket predeterminado de Docker Desktop activado, o la dirección de Docker definida en docker_host
- Un puerto libre en tu equipo, el 8080 de forma predeterminada
- Los archivos de tu sitio web, con un index.html en la raíz (se incluye un sitio de ejemplo)
Versiones
Todas las versiones hasta ahora, de la más reciente a la más antigua.
1.0.0Más reciente
Primera versión del código fuente completo.
- Sirve cualquier carpeta de archivos estáticos desde nginx 1.31 en Docker, en 127.0.0.1:8080 de forma predeterminada.
- Comprueba cada ajuste antes de crear nada y espera hasta que el sitio responde.
- Incluye siete pruebas, un sitio de ejemplo y un archivo de bloqueo para macOS, Linux y Windows.
Source Code Licence
Qué puedes hacer con él
What you may and may not do with the source code you buy.
Leer la licencia completa
- What this licence covers
This licence governs every file included in a product you buy from Dewiride Store: source code, configuration, database scripts, sample data, documentation and any other file in the download. It takes effect when your payment is confirmed and applies to every release of that product that reaches your library. Files that reach your library through an annual updates membership are governed in exactly the same way.
It forms part of the Terms of Sale and Use. Where a product page states different or additional licence terms for that product, those terms prevail for that product. The membership page may likewise state different or additional licence terms for the files a membership carries, and those terms then prevail for those files.
- The licence we grant you
We grant you a perpetual, worldwide, non-exclusive, non-transferable licence to use, reproduce, adapt, translate and modify the files, and to include the result in your own work, on the conditions set out below.
Perpetual means it does not expire. Worldwide means it is not limited to any country. Non-exclusive means we license the same product to other customers. Non-transferable means you cannot pass it on to someone else.
The licence is granted to you — either you personally, or the organisation you identified when buying. Everyone working within that organisation may use the files for that organisation’s projects. Nobody outside it may.
- What you may do
- Use and change the files in your own projects, commercial or otherwise, with no limit on the number of projects.
- Build a product or a service on them and charge your own customers for it.
- Deploy the result for a client, as part of work you are doing for that client.
- Distribute the result in compiled, deployed or otherwise non-source form.
- Keep as many back-up copies as you reasonably need.
- Study, observe and test how the code works, and obtain the information you need to make it work with your own software.
The last two are yours by law under sections 52(1)(aa) to (ac) of the Indian Copyright Act, 1957, and nothing in this licence is intended to take them away.
- What you may not do
- Resell, sublicense, redistribute or publish the files themselves, in whole or in substantial part, in source form.
- Include them in a template, starter kit, course, tutorial repository or component library that you sell or give away, where the code is the thing being supplied.
- Share your account, your download links or your invoices with anyone outside your organisation.
- Publish the files in a public repository, or in any other place where they can be obtained without buying them.
- Remove or obscure the copyright and attribution notices in the source files.
- Use the files to build something whose main purpose is to compete with Dewiride Store as a supplier of the same code.
The distinction that matters is simple: you may sell what you build with the code; you may not sell the code.
- Third-party components
Our products depend on open-source libraries, frameworks and services that we did not write. Those remain under their own licences, which we do not and cannot change. Where a product includes or requires such a component, its licence is named in the product’s documentation, and complying with it is your responsibility.
- Releases
Every release of a product you own is covered by this same licence and appears in your library at no extra cost. A release you have already downloaded remains licensed to you even if we later stop publishing the product. A release that reached your library through an annual updates membership is licensed to you on these same terms, and stays licensed after the period that carried it has ended.
- Ownership
We keep ownership of the files and of the copyright in them. You own whatever you create with them: your changes, your additions and the product you build are yours.
- If this licence ends
This licence ends if you materially breach it and do not put the breach right within thirty days of us asking you to in writing. It also ends if your payment is reversed or refunded, because the purchase it depends on no longer stands. Where a membership period is refunded or reversed, the licence ends for the releases that period carried and for nothing else: anything you bought separately, or that another period carried, is unaffected.
If it ends, you must stop using the files and delete the copies you hold. Work you had already delivered to a client before that point may continue in use, so that ending this licence never breaks something your own customer relies on.
- No warranty beyond the description
The warranties and limits in section 19 and section 20 of the Terms of Sale and Use apply to this licence as well.
- Governing law
This licence is governed by the law of India, and section 24 of the Terms of Sale and Use applies to any dispute about it. If a translation and the English version differ in meaning, the English version governs.
Static Website in Docker with OpenTofu
- 299 INR+ GST, 352,82 INR en total
- 5 US$