Nur Rony
Polyglot Programmer, DevOps and Forever Learner

Run Docker container using Terraform

Run Docker container using Terraform

If you'd like to experiment with Terraform on macOS locally, a great provider for doing so is the Docker provider.

Prerequisities

You must have Docker for Mac and Terraform installed in your machine.

Configure, Plan & Apply!

Start with a basic Nginx Docker container definition in a minimal Terraform configuration — create a main.tf file, and add this to it:

provider "docker" {
  host = "unix:///var/run/docker.sock"
}

# configure nginx image
resource "docker_image" "nginx" {
  name = "nginx:latest"
}

# Create an Nginx container
resource "docker_container" "nginx" {
  image = "${docker_image.nginx.latest}"
  name  = "nginx-server"
  ports {
    internal = 80
    external = 80
  }
}

Save the file, then apply the configuration:

terraform plan

If the plan is good and without error, apply it:

terraform apply

Check to see that the container is running:

docker ps

The output should have something like this:

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                         NAMES
81915ae0cfff        9c914facb54f        "nginx -g 'daemon ..."   10 seconds ago       Up 9 seconds        0.0.0.0:80->80/tcp, 443/tcp   nginx-server