How to use terraform docker provider

How to use terraform docker provider

ยท

2 min read

๐Ÿ–‡๏ธWhat is terraform providers?

In Terraform, a "provider" is a plugin that interacts with various APIs to manage resources. Providers allow Terraform to interact with different cloud platforms, services, and other APIs. Each provider is responsible for understanding API interactions and exposing Terraform resources to users.

Follow below steps to perform terraform providers task:

Step 1: Launch an EC2 Instance

https://lalitakashyapblog.hashnode.dev/step-by-step-guide-to-setting-up-an-ec2-instance

Step 2: Follow below link (till "steps 9") to install terraform

https://lalitakashyapblog.hashnode.dev/terraform-for-beginners-a-comprehensive-guide-to-infrastructure-as-code

Step 3: Install docker using docker provider(create file "vim terraform.tf")

terraform {
  required_providers {
    docker = {
      source = "kreuzwerker/docker"
      version = "3.0.2"
    }
  }
}

provider "docker" {
  # Configuration options
}

Step 4: Terraform init

terraform init

Step 5: Install docker engine

sudo apt-get install docker.io -y

Step 6: Do docker ps

docker ps

Step 7: Give permission to docker

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

Step 8: Create File "vim docker_project.tf"

resource "docker_image" "my_image"{
    name = "trainwithshubham/node-app-batch-6:latest"
    keep_locally = false
}

resource "docker_container" "my_container"{
    image = docker_image.my_image.name
    name = "node-app"
    ports {
        internal=8000
        external=8000
    }
    depends_on = [docker_image.my_image]
}

Step 9: Terraform plan

terraform plan

Step 10: Terraform apply

Confirm when prompted by typing yes.

terraform apply

Step 11: Check docker container created or not

docker ps

Step 12: Give permission to port "8000" in instance

  • Go to security group in instance

  • Click SG link

  • Click on "edit inbound rules"

  • Click on "Add rules"

  • Give "8000" in port range and select "Anywhere" in source and click Save

  • Copy public dns from instance in networking

  • Now go to browser and paste public ip of instance

Step 13: To stop docker container created by terraform

Confirm when prompted by typing yes.

#it will run where all file are peresent
terraform destroy

That's it! You have successfully used Terraform to manage Docker resources. This simple guide helps you automate and manage Docker containers with ease.

Thank you๐Ÿ™

Keep Learning..

ย