Skip to main content

Creating a Pod and Service with Terraform

Hands-On Lab

 

Photo of Travis Thomsen

Travis Thomsen

Course Development Director in Content

Length

01:00:00

Difficulty

Intermediate

One of our customer's web sites has been getting a lot of traffic, and their Docker solution can't keep up. They have requested that we port their blog on Docker over to Kubernetes. To do this, we need to create a new set of Terraform files that can be used to create a Kubernetes pod and service.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Creating a Pod and Service with Terraform

The Scenario

One of our customer's web sites has been getting a lot of traffic, and their Docker solution can't keep up. They have requested that we port their blog on Docker over to Kubernetes. To do this, we need to create a new set of Terraform files that can be used to create a Kubernetes pod and service.

Logging In

Use the IP address and credentials provided on the hands-on lab overview page, and log in with SSH to the server.

There's a fair bit of creating and editing files in this lab. All of the examples here involve using Vim, but use whichever text editor is most comfortable.

Create a Variables File

Create variable.tf:

vi variable.tf

variable.tf contents:

variable "app_label" {
  default     = "ghost-blog"
}

variable "int_port" {
  default     = "2368"
}

variable "ext_port" {
  default     = "8081"
}

variable "image_name" {
  default     = "ghost:alpine"
}

variable "pod_name" {
  default     = "ghost-blog"
}

Create the Main Terraform File

Create main.tf:

vi main.tf

main.tf contents:

resource "kubernetes_service" "ghost_service" {
  metadata {
    name = "ghost-service"
  }
  spec {
    selector {
      app = "${var.app_label}"
    }
    port {
      port = "${var.int_port}"
      target_port = "${var.int_port}"
      node_port = "${var.ext_port}"
    }
    type = "NodePort"
  }
}

resource "kubernetes_pod" "ghost_blog" {
  metadata {
    name = "ghost-pod"
    labels {
      app = "${var.app_label}"
    }
  }

  spec {
    container {
      image = "${var.image_name}"
      name  = "${var.pod_name}"
      port  {
        container_port = "${var.int_port}"
      }
    }
  }
}

Deploy the Infrastructure

Initialize Terraform:

terraform init

Validate the files:

terraform validate

Deploy the pod:

terraform apply -auto-approve

Conclusion

Now if we visit the blog's public IP in a browser, on port 8081 (so, something like http://1.2.3.4:8081), we should see the ghost blog show up. We have successfully set the blog up with Kubernetes. Congratulations!