dockernginxterraformdockerfiledevops

Error: Terraform Docker Image Build Fails with 403 Status Code While Using docker_image Resource


I’ve just started learning Terraform, so to practice a few basic examples, I took on a simple project where I need to write a Terraform configuration file to:

  1. Create a Dockerfile on the local machine with nginx:latest as the base image.
  2. Copy an index.html file from the local directory to the /usr/share/nginx/html directory in the container.
  3. Build a Docker image named "Webserver" and run a Docker container named "webcontainer" on port 5000.
  4. Finally, navigate to https://localhost:5000 to verify the successful deployment. I’ve written the following configuration file, but when I try to execute it with terraform apply, I get the following error:

I tried searching for a solution but couldn't find anything. I came across one answer and tried the troubleshooting steps, but without success. I'm wondering if the issue is related to the Docker Desktop application setup on my windows 11 or if something in my code is causing the problem. Could you please help me resolve this issue?

Error:

Error: failed to read downloaded context: failed to load cache key: invalid response status 403
│
│   with docker_image.webserver,
│   on main.tf line 13, in resource "docker_image" "webserver":
│   13: resource "docker_image" "webserver" {

File Structure:

 Devops
    - main.tf
    - index.html
    - Dockerfile

Code:

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

provider "docker" {}

# Build a Docker image
resource "docker_image" "webserver" {
  name         = "webserver"
  build {
    context    = "~/Desktop/Devops/Dockerfile"
    dockerfile = "~/Desktop/Devops/Dockerfile"
  }
}

# Run a Docker container
resource "docker_container" "webcontainer" {
  image = docker_image.webserver.image_id
  name  = "webcontainer"

  ports {
    internal = 80
    external = 5000
  }
}

# Copy index.html to the directory
resource "local_file" "index_html" {
  filename = "~/Desktop/Devops/index.html"
  content = file("~/Desktop/Devops/index.html")
}

Solution

  • According to docker's documentation: The build context is the set of files that your build can access, to use a local build context, you can specify a relative or absolute filepath.

    In your case:

    So docker_image.webserver resource can be like that:

    resource "docker_image" "webserver" {
      name         = "webserver"
      build {
        context    = "~/Desktop/Devops"
        dockerfile = "Dockerfile"
      }
    }