Terraform Labs · Lab 4 of 9
Run a Web Server in Docker with Terraform
Use the Docker provider to pull a pinned nginx image, create a network and run a container with a port mapping, a health check and a memory limit. Change the page, watch Terraform replace the container, and see how Terraform reacts when someone stops it by hand.
- Environment
- Container
- Level
- Beginner
- Time
- About 35 min
- Cost
- Free
You will build
A running nginx container managed entirely by Terraform, and an understanding of replacement and drift on something you can actually curl.
Before you start
- Lab: Your First Terraform Project: Plan, Apply, Destroy
Docker running on your computer (
docker psworks)Port 18080 free (or pass
-var host_port=...)
Terraform doesn't only manage clouds: any API with a provider works. Docker is the quickest way to manage a real, running service on your own computer — the same lifecycle you'll use for VMs and cloud servers.
How Terraform drives Docker
The docker provider (kreuzwerker/docker) turns your resources into calls to the Docker Engine API,
the same API the docker command uses, through the local socket. It creates three objects: a pinned
image, a user-defined network, and the container attached to it. Their IDs go into
terraform.tfstate, which is how the next plan knows what already exists.
Project structure
docker-web/ ├── .gitignore ├── versions.tf # docker provider ├── variables.tf # name, port, message ├── main.tf # network, image, container └── outputs.tf
Steps
-
1Configure the Docker provider
With no arguments, the provider talks to your local Docker through its default socket.
versions.tf terraform { required_version = ">= 1.6" required_providers { docker = { source = "kreuzwerker/docker" version = "~> 3.0" } } } provider "docker" {} -
2Inputs
variables.tf variable "name" { description = "Container name (also used for the network)" type = string default = "hello-web" } variable "host_port" { description = "Port on your computer that forwards to the container" type = number default = 18080 validation { condition = var.host_port >= 1024 && var.host_port <= 65535 error_message = "Use an unprivileged port between 1024 and 65535." } } variable "message" { description = "Text the web page shows" type = string default = "Hello from Terraform" } -
3Network, image and container
Note the production habits even in a lab: a pinned image tag, the port bound to 127.0.0.1 only, a memory limit, a restart policy and a health check.
keep_locally = truestopsterraform destroyfrom deleting an image other containers might use.main.tf resource "docker_network" "web" { name = "${var.name}-net" } resource "docker_image" "nginx" { name = "nginx:1.28-alpine" # pin a tag, never "latest" keep_locally = true # destroy must not delete an image other containers may use } resource "docker_container" "web" { name = var.name image = docker_image.nginx.image_id restart = "unless-stopped" memory = 128 # MB networks_advanced { name = docker_network.web.name } ports { internal = 80 external = var.host_port ip = "127.0.0.1" # only reachable from this computer } upload { file = "/usr/share/nginx/html/index.html" content = "<h1>${var.message}</h1>\n" } healthcheck { test = ["CMD", "wget", "-qO-", "http://localhost/"] interval = "10s" timeout = "3s" retries = 3 } } -
4Outputs
outputs.tf output "url" { description = "Open this in a browser" value = "http://localhost:${var.host_port}" } output "container_id" { value = docker_container.web.id } -
5Initialise
Run terraform initExpected output
Initializing provider plugins... - Finding kreuzwerker/docker versions matching "~> 3.0"... - Installing kreuzwerker/docker v3.9.0... - Installed kreuzwerker/docker v3.9.0 (self-signed, key ID 0DCE698927DAF8EC) ... Terraform has been successfully initialized!
Hint
Community providers are signed by their authors, so
initsays self-signed rather than HashiCorp. -
6Plan
Run terraform planExpected output
# docker_container.web will be created + resource "docker_container" "web" { + image = (known after apply) + memory = 128 + name = "hello-web" + restart = "unless-stopped" ... + ports { + external = 18080 + internal = 80 + ip = "127.0.0.1" ... } # docker_image.nginx will be created ... # docker_network.web will be created ... Plan: 3 to add, 0 to change, 0 to destroy. Changes to Outputs: + container_id = (known after apply) + url = "http://localhost:18080" -
7Apply and open the page
Your request goes to port 18080 on 127.0.0.1, the host side of the port mapping. Docker forwards it to port 80 inside the container, and nginx answers with the
index.htmlthat Terraform uploaded. Binding to127.0.0.1keeps the page off your network.Request path: host port 18080 is mapped to port 80 inside the container Run terraform apply curl http://localhost:18080 docker ps --filter name=hello-web \ --format 'table {{.Names}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}'Expected output
docker_image.nginx: Creating... docker_network.web: Creating... docker_network.web: Creation complete after 2s [id=76e7f0946d07...] docker_image.nginx: Creation complete after 2s [id=sha256:a8b39bd9cf0f...nginx:1.28-alpine] docker_container.web: Creating... docker_container.web: Creation complete after 1s [id=a16dd777c1ed...] Apply complete! Resources: 3 added, 0 changed, 0 destroyed. Outputs: container_id = "a16dd777c1edbc57ff9371121de37d07322f1088161f2f210112f1610b9a99b9" url = "http://localhost:18080" <h1>Hello from Terraform</h1> NAMES IMAGE STATUS PORTS hello-web a8b39bd9cf0f Up 30 seconds (healthy) 127.0.0.1:18080->80/tcp
Check:curlprints the heading anddocker psshows(healthy)after about 10 seconds. -
8Change the page
Uploaded files are part of the container's definition, so changing the message forces a replacement: Terraform destroys the old container and creates a new one.
Run terraform apply -var 'message=Hello again' curl http://localhost:18080Expected output
# docker_container.web must be replaced -/+ resource "docker_container" "web" { ... - upload { # forces replacement ... + upload { # forces replacement ... Plan: 1 to add, 0 to change, 1 to destroy. ... docker_container.web: Destroying... [id=a16dd777c1ed...] docker_container.web: Destruction complete after 1s docker_container.web: Creating... docker_container.web: Creation complete after 0s [id=67073be7d5ec...] Apply complete! Resources: 1 added, 0 changed, 1 destroyed. ... <h1>Hello again</h1>Check:There's a short gap between destroy and create: that's the downtime a replacement causes.
-
9Cause drift by hand
Stop the container outside Terraform. The provider expects it to be running (
must_run = true), so the next plan reports the change and proposes to put it back.This is drift: the real world no longer matches the state. Every
planstarts with a refresh that reads the real objects, notices the container is gone, and plans to create it again;applybrings back what the code describes.Drift: a manual change is detected by the next plan and repaired by apply Run docker stop hello-web terraform plan -var 'message=Hello again'Expected output
Note: Objects have changed outside of Terraform Terraform detected the following changes made outside of Terraform since the last "terraform apply" which may have affected this plan: # docker_container.web has been deleted - resource "docker_container" "web" { - id = "67073be7d5ecab57aebc316a48e7058259407c8dbf0d4ae314a05cd1bf99e3b2" -> null name = "hello-web" ... # docker_container.web will be created ... Plan: 1 to add, 0 to change, 0 to destroy. -
10Let Terraform repair it
Run terraform apply -var 'message=Hello again' curl http://localhost:18080Expected output
docker_container.web: Creating... docker_container.web: Creation complete after 1s [id=0890332b24d9...] Apply complete! Resources: 1 added, 0 changed, 0 destroyed. ... <h1>Hello again</h1>
-
11Destroy
Run terraform destroy -var 'message=Hello again'Expected output
docker_container.web: Destroying... [id=0890332b24d9...] docker_container.web: Destruction complete after 0s docker_network.web: Destroying... [id=76e7f0946d07...] docker_image.nginx: Destroying... [id=sha256:a8b39bd9cf0f...nginx:1.28-alpine] docker_image.nginx: Destruction complete after 0s docker_network.web: Destruction complete after 3s Destroy complete! Resources: 3 destroyed.
Check:docker ps -a --filter name=hello-weblists nothing. The image stays (keep_locally); remove it yourself withdocker rmi nginx:1.28-alpineif nothing else uses it.
In production
What changes
| In this lab | In production |
|---|---|
| Terraform runs containers on your laptop | Containers run on an orchestrator (ECS, Cloud Run, Azure Container Apps, Kubernetes); Terraform creates the cluster or service, a deploy pipeline ships new images |
| Changing the page replaces the container, with a gap | Rolling or blue-green deploys behind a load balancer: new tasks pass health checks before old ones stop |
| Image pulled from Docker Hub by tag | Image built in CI, scanned, pushed to a private registry (ECR, Artifact Registry, ACR) and referenced by digest |
| Port bound to 127.0.0.1 | Traffic arrives through a load balancer with TLS; containers are on private networks |
Manual docker stop caused drift |
Nobody changes managed resources by hand; scheduled terraform plan in CI reports drift |
Who owns what
Terraform is great at infrastructure that changes slowly (clusters, networks, load balancers, registries).
Application releases that happen many times a day usually belong to a deploy tool (a CI pipeline,
aws ecs update-service, Argo CD). Mixing the two in one apply makes every release an infrastructure change.
Production checklist
- Images pinned by version or digest, never
latest - Every container has memory and CPU limits, a health check and a restart policy
- Only the load balancer is exposed; services listen on private networks
- Images are scanned for vulnerabilities before they're deployed
- Drift is detected by scheduled plans, not by surprise during the next change
Learn the concepts
- Terraform Providers · Terraform Tutorial
- Terraform Resources · Terraform Tutorial
- Terraform State · Terraform Tutorial
- Terraform in Production · Course
- Docker from Basics to Production · Course
Preparing for the Terraform Associate exam? Practice tests and mock exams →