Introduction

The Terraform code you’ve provided is a configuration script for managing infrastructure using Terraform, specifically focused on deploying a Docker container. Let’s break down the components of this script:

Terraform Configuration

  1. Required Providers:
required_providers {
  docker = {
    source  = "kreuzwerker/docker"
    version = "~> 3.0.1"
  }
}
  • This block declares the necessary provider(s) for Terraform to use. Here, it specifies the Docker provider.
  • source: Indicates the source of the provider. Here, “kreuzwerker/docker” is the source, which is a Terraform provider for Docker.
  • version: Specifies the version of the Docker provider. “~> 3.0.1” means any version compatible with 3.0.1.

2. Provider Configuration:

provider "docker" {}
  • This block configures the Docker provider. In this case, it’s an empty configuration, which means it will use default settings.

Resources

  1. Docker Image:
resource "docker_image" "nginx" {
  name         = "nginx"
  keep_locally = false
}
  • This resource block tells Terraform to manage a Docker image.
  • name: The name of the Docker image, in this case, “nginx”.
  • keep_locally: A boolean indicating whether to keep the image locally after it’s been pulled. false means it won’t be kept.

2. Docker Container:

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "tutorial"

  ports {
    internal = 80
    external = 8000
  }
}

This resource block manages a Docker container.

  • image: Specifies the image to be used for the container. It refers to the image_id of the docker_image.nginx resource, ensuring it uses the image pulled in the previous step.
  • name: The name of the container, set as “tutorial”.
  • ports: Defines the port mapping.
  • internal: The port inside the container (80, the standard port for HTTP).
  • external: The port on the host that maps to the internal port (8000).

The full terraform script main.tf:

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

provider "docker" {}

resource "docker_image" "nginx" {
  name = "nginx"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name = "tutorial"
  ports {
    internal = 80
    external = 8000
  }
}

Conclusion

This Terraform script is used to deploy an Nginx server inside a Docker container. It first pulls the Nginx image from Docker Hub, then creates a container from this image, mapping the internal port 80 of the container to port 8000 on the host machine. This is a common setup for deploying web servers in containerized environments.