Skip to content

Lab: Terraform + Docker

Pairs with: Infrastructure as Code, Terraform

Real Terraform, managing real containers on your local Docker daemon via the kreuzwerker/docker provider. Every concept from the two pages above is reproducible here: plan/apply, idempotency, drift, forced replacement, blast radius via count — with zero AWS/GCP/Azure account needed.

Needs Terraform in addition to Docker: brew tap hashicorp/tap && brew install hashicorp/tap/terraform.

main.tf

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0"
    }
  }
}

provider "docker" {}

resource "docker_image" "nginx" {
  name = "nginx:1.27"
}

resource "docker_container" "web" {
  count = var.web_count
  name  = "tf-web-${count.index}"
  image = docker_image.nginx.image_id

  ports {
    internal = 80
    external = 8080 + count.index
  }
}

variables.tf

variable "web_count" {
  description = "Number of nginx containers to run"
  type        = number
  default     = 2
}

outputs.tf

output "container_names" {
  value = docker_container.web[*].name
}

output "urls" {
  value = [for c in docker_container.web : "http://localhost:${c.ports[0].external}"]
}

Exercises

The full walkthrough (idempotent re-apply, real drift detection, scaling via a variable without touching existing resources, a real -/+ forced-replacement plan) lives in the lab's README:

labs/terraform-docker/README.md on GitHub

git clone https://github.com/sanketn26/interview-prep
cd interview-prep/labs/terraform-docker
export DOCKER_HOST=$(docker context inspect -f '{{.Endpoints.docker.Host}}')
terraform init
terraform apply

← All Labs