# Day 62 - Terraform and Docker

**Task-01: Create a Terraform script with Blocks and Resources**

In today's Terraform project, we'll explore how to combine the power of Terraform with Docker to manage containerized applications. Let's get started!

First, we need to define the required provider for Docker in our Terraform script:

```bash
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 2.21.0"
    }
  }
}
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687749172428/ce0dfc0b-3d85-40af-9c0b-95df1b3fa7bd.png align="center")

**Task-02 : Create a resource Block for an nginx docker image**

Next, let's create a resource block to define an NGINX Docker image and a corresponding container:

```bash
required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 2.21.0"
    }
  }
}

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

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

In this example, we're pulling the latest NGINX image and creating a container named "tutorial" with port mapping from internal port 80 to external port 80.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687750017222/b889a536-48bc-4b7f-8de7-a194639f8b21.png align="center")

Before applying the Terraform script, ensure that Docker is installed on your system and run the following command to grant necessary permissions:

```bash
sudo chown $USER /var/run/docker.sock
```

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687750137779/fe89ecbf-b16c-4a4c-b399-515313710a00.png align="center")

Now, let's run the Terraform commands:

Run `terraform plan` to preview the changes that Terraform will make.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687750198874/387842dd-f28c-418e-a927-824629767703.png align="center")

Run `terraform apply` to apply the changes and create the Docker container.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687750281928/b4c40266-25a8-4b39-9757-537b2bb29f6a.png align="center")

Once the process completes, your NGINX Docker image will be up and running, ready to serve your web applications.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1687750352885/16e37f88-3af9-4200-8ca3-2f3890aab362.png align="center")

That's all for today's Terraform and Docker integration. If you have any questions or need further assistance, feel free to comment below.

#Terraform #Docker #Containerization #InfrastructureAsCode #DevOps #CloudComputing #Automation #CloudDeployment #DevOpsJourney #ContinuousIntegration #ContinuousDelivery #CloudManagement #CloudInfrastructure #InfrastructureAutomation #DevOpsCulture
