As ZachEddy and thaJeztah mentioned in one of the issues you linked to, you can label the intermediate images and docker image prune those images based on this label.
Dockerfile (using multi-stage builds)
FROM node as builder
LABEL stage=builder
...
FROM node:dubnium-alpine
...
After you’ve built you image, run:
$ docker image prune --filter label=stage=builder
For Automation Servers (e.g. Jenkins)
If you are running the builds in an automation server (e.g. Jenkins), and want to remove only the intermediate images from that build, you can
- Set a unique build ID as an environment variable inside your Jenkins build
- Add an
ARGinstruction for this build ID inside yourDockerfile - Pass the build ID to
docker buildthrough the--build-argflag
FROM node as builder
ARG BUILD_ID
LABEL stage=builder
LABEL build=$BUILD_ID
...
FROM node:dubnium-alpine
...
$ docker build --build-arg BUILD_ID .
$ docker image prune --filter label=stage=builder --filter label=build=$BUILD_ID
If you want to persists the build ID in the image (perhaps as a form of documentation accessible within the container), you can add another ENV instruction that takes the value of the ARG build argument. This also allows you to use the similar environment replacement to set the label value to the build ID.
FROM node as builder
ARG BUILD_ID
ENV BUILD_ID=$BUILD_ID
LABEL stage=builder
LABEL build=$BUILD_ID
...
FROM node:dubnium-alpine
...