DEV Community

Udoh Deborah
Udoh Deborah

Posted on

Day 62: Terraform and Docker

Step-by-Step guide to provisioning a Docker container running an Nginx web server using Terraform:

Step 1: Install Terraform and Docker
Install Terraform on your machine by downloading the binary from the official Terraform website or using a package manager like Homebrew (for macOS) or apt-get (for Linux).
Install Docker on your machine by downloading the Docker Desktop application (for macOS or Windows) or using a package manager like apt-get (for Linux).

Step 2: Create a New Terraform Configuration File
Create a new file named in an empty directory. This file will contain your Terraform configuration.
Open the file in a text editor.

  1. Step 3: Specify the Docker Provider Add the following code to the main.tf file to specify the Docker provider:
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 2.21.0"
    }
  }
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Configure the Docker Provider
Add the following code to the main.tf file to configure the Docker provider:

provider "docker" {}
Enter fullscreen mode Exit fullscreen mode

Step 5: Pull the Nginx Docker Image
Add the following code to the main.tf file to pull the Nginx Docker image:

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

Enter fullscreen mode Exit fullscreen mode

Step 6: Create a Docker Container
Add the following code to the main.tf file to create a Docker container from the Nginx image:

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

Enter fullscreen mode Exit fullscreen mode

Step 7: Initialize Terraform
Open a terminal in the directory where your main.tf file is located.
Run the command terraform init to initialize Terraform.

Step 8: Apply the Terraform Configuration
Run the command terraform apply to apply the Terraform configuration.
Review the plan and type yes to confirm.

Step 9: Verify the Docker Container
Run the command docker ps to verify that the Docker container is running.
Open a web browser and navigate to http://localhost:80 to access the Nginx web server.

Step 10: Clean Up
When you're finished, run the command terraform destroy to destroy the Docker container and image.
That's it! You've successfully provisioned a Docker container running an Nginx web server using Terraform.

Top comments (0)