
This assumes you have installed Terraform, as described at https://learn.hashicorp.com/tutorials/terraform/install-cli?in=terraform/aws-get-started and that you have also installed Docker on Linux and Docker is running.
Let's create a directory that will contain the main.tf file that will be used to create an Nginx container on Docker.
mkdir /usr/local/terraform/nginx/docker
cd /usr/local/terraform/nginx/docker
Create the main.tf file.
touch main.tf
And the add the following to main.tf. Let's break this down.
- Provider kreuzwerker/docker will be used for Docker
- The lastest version of image nginx will be pulled down
- The nginx container will be created and started, listening on port 80 in the container and port 8000 on the Docker server
terraform {
required_providers {
docker = {
source = "kreuzwerker/docker"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.latest
name = "nginx"
ports {
internal = 80
external = 8000
}
}
You may need to reissue the terraform init command
~]# terraform init
Initializing the backend...
Initializing modules...
Initializing provider plugins...
Terraform has been successfully initialized!
The terraform plan command can be used to see what Terraform will try to do.
terraform plan
By default, the terraform.tfstate file should be found in your root module directory (/usr/local/terraform/nginx/docker in this example).
- If the Nginx container does not exist and the terraform.tfstate file does not contain the Nginx container, Terraform will create the Nginx container.
- If the Nginx container exists and the terraform.tfstate file contains the Nginx container and a difference is found between the main.tf file and the terraform.tfstate file, Terraform will update the Nginx container.
- If the Nginx container exists and the terraform.tfstate file contains the Nginx container and the Nginx container is removed from the main.tf file, Terraform will destroy (delete) the Nginx container.
The terraform apply command from your root module directory (/usr/local/terraform/nginx/docker in this example) can be used to create or update the image and Nginx container.
terraform apply
The docker images command should include the Nginx image.
~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
nginx latest 105b54dc64f1 32 hours ago 253 MB
The docker container command should show the nginx container is up and running.
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1a474bc0811b nginx "/docker-entrypoint.…" 2 minutes ago Up 2 minutes 0.0.0.0:80->80/tcp, :::80->80/tcp nginx
You should now be able to get the Nginx landing page at http://<hostname or IP address of your Docker server>:8000.
Did you find this article helpful?
If so, consider buying me a coffee over at