Leverage Terraform to Automate Docker Images and Container Builds

935 VIEWS

· · ·

This guide teaches how to leverage Terraform to automate Docker images and container builds.

One of the great tools to containerize your application is Docker. It allows developers to package and run applications along with their runtime dependencies in isolated environments that containers offer. With Docker, teams can develop, ship, and run applications separately from their infrastructure. Allowing them to create independently deployable services to deliver software faster.

Docker being a great tool for containerization, managing and working with multiple Docker containers can get out of hand. Tools such as Terraform provide automation and infrastructure as code (IaC) features. Terraform is an excellent choice for empowering your infrastructure while leveraging Docker. 

Prerequisites

To comfortably follow along with this guide ensure you have the following tools installed and ready based on your OS environment:

  • Docker Engine: You will use Docker images and containers. Ensure Docker is installed, up, and running on your computer.
  • Terraform: You are utilizing terraform for Docker Terraform integration. Ensure you have Terraform correctly installed on your computer.

Once you confirm that the above tools are ready, let’s dive in and automate Docker images and containers using Terraform configuration files.

Additionally, you need a working project ready. If you don’t have one, we will create a simple example here. We will use the application and run it through Terraform to create the application image and container using Docker. In this guide, you will create a basic React.js app. Therefore, ensure you have a Node.js runtime installed on your computer.

Setting Up a Basic Application

To demonstrate how to automate tasks using terraform. Let’s get a simple React.js application running. If you have an applicationready, you can skip this step and use the application alongside this guide.

Navigate to where you want your application to live and run the following command to create a basic React app:

npx create-react-app react-app

A react-app directory will be created containing your application. Change the directory and point to this newly created folder:

cd react-app

To test this application run:

npm start

Open http://localhost:3000/ on your browser and check if the application is working. You should be served with the following basic web app:

It is good to note that Terraform will set up and automate configuration files to run the above app with Docker. Therefore, Docker should serve us with the same application.

Creating Dockerfile for This Application

Terraform will check the application Docker command and instruct Docker what is need to be done. Dockerfile will contain these Docker instructions and use them to create a Docker image. Let’s create one for the above application. First, you need to create a production build of this application to optimize it to run a light Docker image. A production-ready application creates images of smaller sizes

Inside the react-app directory run:

npm run build

Then create an app.dockerfile file within the same react-app directory. Inside this file add the following Docker instructions:

FROM nginx:stable-alpine
COPY build/ /usr/share/nginx/html

Note: Each application Dockerfile differs. Therefore, always ensure you have the right Dockerfile for running your application. If you are using a different application, ensure your app.dockerfile file reflects as such. Let’s now dive and Leverage terraform to automate Docker images and container builds.

Creating Terraform Provider Configuration File

First, you need to create a list of required providers for your infrastructure. A provider in Terraform is a plugin that enables interaction with an API. This includes Cloud providers and Software-as-a-service providers. In this case, you need a Terraform Docker provider. Terraform will use this provider to communicate with Docker. Inside your working folder create an infra directory and add a providers.tf file. Then create your Docker Terraform as follows:

# Declare the Docker provider
terraform {
  required_providers {
    # Set the required provider and versions
    docker = {
      source = "kreuzwerker/docker"
      version = "2.22.0"
    }
  }
}

# Add the Docker provider configurations
provider "docker" {
  # Configuration options
  host = "npipe:////.//pipe//docker_engine"
}

Terraform will use this code to install the stated provider.

Note: Each provider is released independently from Terraform itself. You can always check this Terraform Docker provider and copy the needed Terraform configuration for Docker.

Leverage Terraform to Automate Docker Images

Using the above provider, let’s create a Terraform task that will automate Docker image creation for the application.

Inside the infra directory, create a main.tf file and add the Terraform code that will create the Docker image resource as follows:

# Create a docker image resource
resource "docker_image" "react_image" {               
  name = "react_image"
  build {  
    path = "../react-docker"
    dockerfile = "app.dockerfile"
  }
}

Here the docker_image will create an image called react_image. You need to ensure you don’t have any image named react_image in your Docker. You can run the following command to check that:

docker image ls react_image

The build block executes a path property and points it to the path where the Docker context is. In this case, the app.dockerfile, points specific Docker configuration file for the application.

Let’s go ahead and test this out. First, terraform needs to download the above created provider. The following command will do exactly that.

If executing the above command was successful, a Terraform has been successfully initialized! message will be logged on your terminal. Also, Note if you have previously executed Docker terraform provider with a different version, you may encounter the following error:

The next command checks if the configuration code is correct based on the resources you have created. Run the following command to check that:

terraform plan

To apply the above resource and provision them to Docker, run the following command:

terraform apply

This will summarize the actions Terraform will perform:

Go ahead and Enter a value. In this case only ‘yes’ will be accepted to approve.

Terraform will create a task that will perform the described resource and create a Docker image for your application.

To confirm that indeed the image was created, run the following command:

docker images

Alternatively, you can check your Docker engine images:

Indeed, terraform has automated this task and the image for this application is now available in Docker. Using this image, you can create a container to run the application.

Leverage Terraform to Automate Containers Builds

If you are creating a container using the Docker way, you would have used the following command as an example:

docker run -d -p 8080:80 react_image

This way Docker will execute the internal port 80 and external port 8080 of the container that will execute the react_image image. However, you can still leverage Terraform and create a job to automate Docker containers.

Create another resource for a container task. Inside the main.tf file, add the following:

# Create a docker container resource
resource "docker_container" "react_container" {   
  # the name of the container
  name = "react_container"  
  image = docker_image.react_image.image_id
    ports {
    internal = "80"
    external = "8080"
  }
}

Here, terraform will instruct Docker to create a react_container using docker_image. This container will be exposed to internal port 80 and external port 8080.

Run the following command to check if the configurations are correct:

terraform plan

 

To apply the changes to Docker run:

terraform apply

At this point, you should have the container ready within Docker. To confirm that run:

To test the application container open “ on the browser. At this point, you should be served with the same application created earlier. But this time served directly from Docker.

And yes, this was a success!!

Conclusion

Congratulations! You have successfully automated the Docker task using a Terraform Docker integration. You can now go ahead and try other resources such as:

I hope you found how to leverage Terraform to automate Docker images and container builds. helpful! For any code references used in this code, check out this GitHub repository.


Joseph is fluent in Fullstack web development and has a lot of passion for DevOps engineering. He loves to write code and document them in blogs to share ideas.


Discussion

Click on a tab to select how you'd like to leave your comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Menu
Skip to toolbar