Docker build does not remove temporary images when building a multi-stage docker file

Viewed 1916

I have a docker file that builds my .Net Core API in a temporary image and then creates an image with the generated files. As far as I know, the temporary image should be removed automatically but in my tests it was not removed. I use Docker Desktop for Windows. The docker file, image list before running it and after running it are as follows;

Docker file;

FROM mcr.microsoft.com/dotnet/core/sdk:2.2-alpine AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM mcr.microsoft.com/dotnet/core/aspnet:2.2-alpine
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "CoreAPI1.dll"]

Image list before running;

PS D:\temp\CoreAPI1\CoreAPI1> docker image ls                                                                           
REPOSITORY                             TAG                 IMAGE ID            CREATED             SIZE
mcr.microsoft.com/dotnet/core/sdk      2.2-alpine          3a2253204e79        4 weeks ago         1.48GB
mcr.microsoft.com/dotnet/core/aspnet   2.2-alpine          820b2f3a9c7a        4 weeks ago         168MB
PS D:\temp\CoreAPI1\CoreAPI1>

Commands tested;

docker build -t coreapi1 .
docker build --rm -t coreapi1 .

Image list after building the docker file;

PS D:\temp\CoreAPI1\CoreAPI1> docker image ls                                                                           
REPOSITORY                             TAG                 IMAGE ID            CREATED             SIZE
coreapi1                               latest              d8cb00730c52        3 minutes ago       168MB
<none>                                 <none>              1105d14991b3        3 minutes ago       1.48GB
mcr.microsoft.com/dotnet/core/sdk      2.2-alpine          3a2253204e79        4 weeks ago         1.48GB
mcr.microsoft.com/dotnet/core/aspnet   2.2-alpine          820b2f3a9c7a        4 weeks ago         168MB
PS D:\temp\CoreAPI1\CoreAPI1>

See the image with name and tag none.

Docker version is 19.03.2. What may be the reason? How can I prevent this dangling image being left after the build?

2 Answers
for image in $(docker images -f "dangling=true" -q)
do
    docker rmi -f $image
done

or docker images -q -f "dangling=true" | xargs docker rmi

The key here is the "dangling=true" filter, which shows exactly those intermediary images used during the building stage.

docker image rm [OPTIONS] IMAGE [IMAGE...]

Options

--force , -f        Force removal of the image
--no-prune      Do not delete untagged parents
Related