To use the Terraform Docker provider, you define the provider configuration and then use its resources (like docker_image and docker_container) to manage Docker components. The process involves writing the configuration file, initializing the project, and applying the changes.
Before starting, ensure you have the following installed:
- Terraform CLI
- Docker CLI and Daemon (e.g., Docker Desktop, configured with a default profile)
Create a new directory for your Terraform project and navigate into it:
mkdir terraform-docker
cd terraform-dockerCreate a file named main.tf in this directory, where all the configuration will go.
Open main.tf in a text editor and add the following configuration. This configuration specifies the required provider and defines resources to pull an NGINX image and run it in a container, exposing port 8080 externally.
# main.tf
# Define the required providers and their versions
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
version = "~> 3.0"
}
}
}
# Configure the Docker provider (uses local Docker socket by default)
provider "docker" {}
# Define a data source to pull the NGINX image
data "docker_image" "nginx" {
name = "nginx:latest"
}
# Define a resource to create and manage a Docker container
resource "docker_container" "nginx_container" {
name = "nginx_example"
image = data.docker_image.nginx.image_id
ports {
internal = 80
external = 8080
}
}
- Provider Block: Tells Terraform to use the
kreuzwerker/dockerprovider. - Data Source
docker_image: Instructs Terraform to fetch the specified Docker image (nginx:latest). It ensures the image is available before attempting to create a container. - Resource
docker_container: Defines the container to run, linking it to the image data source and mapping internal port80to external port8080.
Run terraform init in your terminal. This command downloads the Docker provider plugin.
terraform initReview the changes Terraform plans to make using terraform plan.
terraform planIf the plan looks correct, apply the configuration to create the Docker container.
terraform applyType yes when prompted to confirm the action.
After Terraform finishes, the NGINX container will be running. You can verify this by visiting http://localhost:8080 in your web browser or by running the Docker CLI command:
docker ps -aTo remove the created container and the image, run terraform destroy. This cleans up all resources managed by your Terraform configuration.
terraform destroyTerraform Variables