--- title: "How to Manage Docker Containers with Terraform on Ubuntu" description: "Install Terraform on Ubuntu 24.04 and use the kreuzwerker/docker provider to define images, networks, volumes and containers as code, then plan and apply them." category: "Automation and IaC" language: en source: https://cubepath.com/docs/automation-and-iac/terraform-with-docker-provider updated: 2026-09-25 --- # How to Manage Docker Containers with Terraform on Ubuntu Terraform is usually associated with cloud APIs, but the community `kreuzwerker/docker` provider lets it drive a Docker Engine directly. Instead of a sequence of `docker run` commands, you describe images, networks, volumes and containers in HCL files, review the changes with `terraform plan`, and let Terraform bring the host to that state. In this tutorial you will install Terraform on Ubuntu 24.04 and deploy a small stack (an Nginx web container and a PostgreSQL database on a private network with a persistent volume) entirely from Terraform code. ## Prerequisites To follow this tutorial you need: - A server running Ubuntu 24.04 LTS, such as a CubePath VPS, with a non-root user that has `sudo` privileges. - Docker Engine installed from Docker's official repository, with your user in the `docker` group so it can use `/var/run/docker.sock` without `sudo`. Run `docker run --rm hello-world` to confirm it works. - Basic familiarity with Docker concepts (images, containers, volumes). ## Step 1 - Installing Terraform HashiCorp publishes an official APT repository. Install the tools needed to add it: ```bash sudo apt update sudo apt install -y gnupg curl lsb-release ``` Download the HashiCorp signing key into a dedicated keyring: ```bash sudo install -m 0755 -d /etc/apt/keyrings curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/hashicorp.gpg ``` Add the repository, restricted to that key: ```bash echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/hashicorp.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list ``` Install Terraform: ```bash sudo apt update sudo apt install -y terraform ``` Check the installed version: ```bash terraform version ``` ```output Terraform v1.13.3 on linux_amd64 ``` Your version number will likely be newer. Anything from 1.5 onward works with this tutorial. ## Step 2 - Configuring the Docker provider Create a directory for the project. Each Terraform project lives in its own directory and all `.tf` files in it are loaded together: ```bash mkdir -p ~/docker-stack cd ~/docker-stack ``` Create `versions.tf`, which pins the provider and tells it how to reach the Docker daemon: ```bash nano versions.tf ``` ```hcl terraform { required_version = ">= 1.5" required_providers { docker = { source = "kreuzwerker/docker" version = "~> 3.0" } } } provider "docker" { host = "unix:///var/run/docker.sock" } ``` The `~> 3.0` constraint accepts any 3.x release but not a future 4.0 with breaking changes. The `host` value points at the local Docker socket. To manage a remote host instead, you can use an SSH URL such as `ssh://your_user@your_server_ip`, which reuses your SSH keys and avoids exposing the Docker API over TCP. Initialize the project so Terraform downloads the provider: ```bash terraform init ``` ```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 BD080C4571C6104C) ... Terraform has been successfully initialized! ``` Terraform also creates `.terraform.lock.hcl`, which records the exact provider version. Commit it to version control so everyone uses the same build. ## Step 3 - Declaring variables and outputs The database password should not be hardcoded in the configuration. Declare it as a sensitive variable, together with the host port for the web container: ```bash nano variables.tf ``` ```hcl variable "db_password" { description = "Password for the PostgreSQL appuser account" type = string sensitive = true } variable "web_port" { description = "Host port that publishes the web container" type = number default = 8080 } ``` Marking the variable `sensitive` hides it in `plan` and `apply` output. It is still stored in plain text in the state file, which is why `terraform.tfstate` must never be committed to Git. Now create `outputs.tf` so Terraform prints useful values after each apply: ```bash nano outputs.tf ``` ```hcl output "web_url" { value = "http://127.0.0.1:${var.web_port}" } output "db_container" { value = docker_container.db.name } ``` ## Step 4 - Defining the network, volume and images Create `main.tf` with the shared resources first. A user-defined network gives the containers DNS resolution by container name, and a named volume keeps the database files when the container is replaced: ```bash nano main.tf ``` ```hcl resource "docker_network" "app" { name = "app-network" } resource "docker_volume" "db_data" { name = "app-db-data" } resource "docker_image" "postgres" { name = "postgres:17" keep_locally = true } resource "docker_image" "nginx" { name = "nginx:1.28" keep_locally = true } ``` The `docker_image` resources pull the images. Pin specific tags instead of `latest` so that a plan never changes silently because upstream pushed a new image. With `keep_locally = true`, `terraform destroy` leaves the images in the local cache. ## Step 5 - Defining the containers Append the two containers to `main.tf`: ```hcl resource "docker_container" "db" { name = "app-db" image = docker_image.postgres.image_id restart = "unless-stopped" env = [ "POSTGRES_USER=appuser", "POSTGRES_PASSWORD=${var.db_password}", "POSTGRES_DB=appdb", ] networks_advanced { name = docker_network.app.name } volumes { volume_name = docker_volume.db_data.name container_path = "/var/lib/postgresql/data" } healthcheck { test = ["CMD-SHELL", "pg_isready -U appuser -d appdb"] interval = "10s" timeout = "5s" retries = 5 } } resource "docker_container" "web" { name = "app-web" image = docker_image.nginx.image_id restart = "unless-stopped" ports { internal = 80 external = var.web_port ip = "127.0.0.1" } networks_advanced { name = docker_network.app.name } upload { content = "