Space is not getting reclaimed

WORKDIR /usr/src/app

COPY TestFolder.zip TestFolder.zip

RUN mvn clean package -DskipTests &&
apt-get update &&
apt-get -y install iproute2 &&
apt-get install -y iputils-ping &&
apt-get install -y tcpdump &&
rm -rf TestFolder.zip

I have copied TestFolder.zip to destinatination and space is allocated but when I have deleted “rm -rf TestFolder.zip” the space is not reclaimed. As a result, the image size is getting larger due to copy.
Use case: Copied an rpm and after installation of the rpm package while deleting the original rpm the space is not reclaimed.

How could I reclaim the space?

Each COPY, ADD or RUN instruction will create a new layer. Files written in a layer, but deleted in a later layer, will only be marked as deleted. They will still physically exist in the layer they were written. A container created from that image will not see any files that are marked as deleted.

You need to make sure a file is created and deleted within the same layer. That’s why people usually download files from a http source, uncompress it and delete it in the same RUN instruction.

If you could switch from zip compress to tar, you could use the ADD instruction to extract the archive while adding it’s content to the image:

Just to be clear: it does not work with zip files.

2 Likes

Thanks for the quick reply.
Is it feasible to use COPY within RUN mean in the same layer?

You might want to re-read my post, as it should have addressed this question in the first sentence.

Just to be sure: the answer is no.

Yes, I got your point. Thanks so much!!!

I have changed my Docker file as instead of copying the .tar file I am copying the complete folder as below.

Case-1
Layer-1: COPY TestFolder/ /DT/temp/IDAP

Layer-2: RUN mvn clean package -DskipTests &&
cd /DT/temp/IDAP/NewFolder &&\
apt-get update &&
apt-get -y install iproute2 &&
apt-get install -y iputils-ping &&
apt-get install -y tcpdump

Instead of

Case-2
Layer-1: COPY TestFolder.tar.gz /DT/temp/TestFolder.tar.gz

Layer-2: RUN mvn clean package -DskipTests &&
tar -C /DT/rel/IDAP/ -xvf /DT/temp/TestFolder.tar.gz &&
rm -rf /DT/temp/TestFolder.tar.gz &&
cd /DG/activeRelease/IDAP/NewFolder &&\
apt-get update &&
apt-get -y install iproute2 &&
apt-get install -y iputils-ping &&
apt-get install -y tcpdump

My expectation is the size for layer Layer-2: will be decreased in Case-1, but actually it’s not happening.
Getting same image size for Case-1 and Case-2
My expectation was the size ocupied for the operation tar -C /DT/rel/IDAP/ -xvf /DT/temp/TestFolder.tar.gz was decreased. Is my expectation wrong?

Could you please guide me.
Note: I am using Azure RHEL8 system.