I was following a tutorial on terraform.io that has me provision a docker image and container using terraform, and then destroy the terraform stack. However, I get the following error:
Error: Unable to remove Docker image:
Error response from daemon: conflict: unable to delete 540a289bab6c (must be forced) -
image is being used by stopped container ae12197d265d
I know the native Docker solution to this is just running docker rmi -f 540a289bab6c
. However, I was wondering if there's a terraform approach to this?
The docs for the terraform resource docker_image
show the reason terraform attempted to destroy the image upon terraform destroy
: the template main.tf
had keep-locally
set to true
. But it doesn't say how to force that destruction.
The main.tf
from the tutorial is as follows:
terraform {
required_providers {
docker = {
source = "terraform-providers/docker"
}
}
}
provider "docker" {}
resource "docker_image" "nginx" {
name = "nginx:latest"
keep_locally = false
}
resource "docker_container" "nginx" {
image = docker_image.nginx.latest
name = "tutorial"
ports {
internal = 80
external = 8000
}
}
So how do I force terraform destroy
to work on this template without resorting to manual intervention using docker native tools?
The error message indicates that there is another container relying on the same image. It could be that a separate docker container provisioned outside of terraform and using the same nginx docker image in the tutorial. Check your docker ps -a
to see if there is such container if so just run docker rm -f <container_name>
to remove it and your terraform destroy should work.