Automatically remove FROM image used in multi stage Dockerfile

Viewed 107

My automated build has a multi-stage Dockerfile with this:

FROM foo/bar:1.2.3 as builder
LABEL stage=builder           # <-- labels intermediate image, not FROM image
#...

After the build I run docker image prune --filter label=stage=builder --force to remove the intermediate image.

Can I also delete the FROM image foo/bar:1.2.3 at the same time? I don't care about caching.

I'm not referring to docker image rm foo/bar:1.2.3 - I want to delete it inside the Dockerfile after that stage, or remove it via a label or something like that (as done for the intermediate image).

1 Answers

I couldn't find a supported approach, so here's my workaround.

My build script:

#!/bin/bash

# build image
# ...

# get environment variables from .env
set -o allexport
. .env
set +o allexport

# get images to remove from Dockerfile
IMAGES=($( \
  cat Dockerfile | \
  grep '^FROM [[:alpha:]]' |
  cut -d' ' -f2 |
  xargs -i bash -c "echo {}"
))

# remove images
echo "${IMAGES[@]}" | \
  xargs -r -n1 docker image rm || true
Related