Cannot connect to docker daemon

I had the same problem but finally managed to fix. Before running terraform apply, check where the docker daemon is running using docker context ls. The default option may not work, thus the error most people get. Pick the one with *. Then go to the file <main.tf>, edit it to reflect the host as below:

terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 3.0.1"
    }
  }
}

provider "docker" {
  host = "unix:///Users/bett/.docker/run/docker.sock" //specifying where the docker daemon is running
}

resource "docker_image" "nginx" {
  name         = "nginx"
  keep_locally = false
}

resource "docker_container" "nginx" {
  image = docker_image.nginx.image_id
  name  = "tutorial"

  ports {
    internal = 80
    external = 8000
  }
}

Sorry for the poorly formatted explanation, not familiar with code formatting here.