The Docker Provider enables Terraform to manage Docker resources, such as containers, images, networks, and volumes. This provider simplifies the automation and orchestration of containerized applications, making it a key tool for teams working with Docker-based environments.
Key Features:
Example Use Case: Running a Docker Container
Here’s how to pull an NGINX image and run it as a container using the Docker Provider:
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
}
resource "docker_container" "nginx" {
name = "example-nginx"
image = docker_image.nginx.latest
ports {
internal = 80
external = 8080
}
}
What’s Happening Here?
provider
block initializes the Docker Provider for local Docker management.docker_image
resource pulls the latest version of the NGINX image.docker_container
resource creates and starts a container named example-nginx
, exposing it on port 8080.Advanced Tip:
Set up a Docker network to connect multiple containers:
resource "docker_network" "example" {
name = "example-network"
}
resource "docker_container" "app" {
name = "example-app"
image = "my-app-image"
networks_advanced {
name = docker_network.example.name
}
}
resource "docker_container" "db" {
name = "example-db"
image = "postgres:latest"
networks_advanced {
name = docker_network.example.name
}
}
This configuration creates a custom Docker network and connects both the app
and db
containers to it, enabling inter-container communication.