Dangling images using docker-compose

Is it possible to avoid creating dangling images while using the docker-compose build command and without always using the docker image prune command to remove them manually?

I don’t think so, but this is independent from Docker Compose. When you build an image after changing something in the sourcecode, you get a new image. It does not mean you change the old image, it only means you create a new image, remove the tag from the old image and add it to the new image. If you build frequently, you can create a script that gets the ID of the current image, runs the build and removes the old image by the previously saved ID.

docker-build-wrapper.sh

#!/bin/bash

id=$(docker image inspect "$image_name" --format '{{ .ID }}')
docker compose build
new_id=$(docker image inspect "$image_name" --format '{{ .ID }}')
if [[ "$id" != "$new_id" ]]; then 
  docker image rm "$image_name"
fi

The above code is just an improvised code without testing, so you may need to fix it before using.

1 Like