Docker with Terraform

Docker with Terraform

Day 62 of #90DaysOfDevOps

Task-01

  • Create a Terraform script with Blocks and Resources for docker.

Task-02

  • Create a resource Block for an nginx docker image.

  • Create a resource Block for running a docker container for nginx.


Create a Terraform script with Blocks and Resources for docker.

Create a file <main.tf> then enter the code:

terraform {
    resource_providers {
        docker = {
            source = "nginx:latest"
            version = "~> 2.15.0"
        }
    }
}

Create a resource Block for an nginx docker image.

Continue writing of the code in the same file as above:

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

Create a resource Block for running a docker container for nginx.

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

Initiate terraform with terraform init

Run the file with terraform apply

Verify it by writing command docker ps

Before running the commands, make sure Docker and Terraform are installed in your system. If it isn't, then you can refer: Docker Install and Terraform Install

Here are some practical screenshots:

Thanks for Reading!