Docker images are built in layers. Each layer is a snapshot of the filesystem at a particular point in the build process. When you build a Docker image, the RUN. The commands in the Dockerfile are executed in order, and each command creates a new layer.
Let's say that you have the following Dockerfile:
FROM alpineRUN mkdir dirRUN wget http://google.comRUN rm -r dir
Line 3: This will create the directory dir in the first layer.
Line 4: The wget command will download the Google home page to the dir directory. 
Line 5: The rm -r dir command will try to remove the dir directory from the previous layer.
Note: The
rm -r dircommand will fail because the directorydiris not present in the current layer. The directorydirwas created in the previous layer, and it is not accessible from the current layer.
There are a few ways to work around this issue.
WORKDIR command:One way is to use the WORKDIR command to change the current working directory. This will make the rm -r dir command affect the directory in the previous layer.
FROM alpineRUN mkdir dirWORKDIR dirRUN wget http://google.comWORKDIR /RUN lsRUN rm -r dir
Line 3–4: This will create the directory dir in the first layer, and then change the current working directory to dir. 
Line 5: The wget command will download the Google home page to the dir directory. 
Line 7: The ls command will list the contents of the current working directory, which will include the dir directory. 
Line 8: The rm -r dir command will remove the dir directory from the previous layer.
VOLUME command:Another way to work around this is to use a volume. A volume is a special type of filesystem that is not part of the Docker image. This means that you can create a volume, copy the directory you want to remove to the volume, and then remove the directory from the image.
FROM alpineRUN mkdir dirVOLUME /vol# Copy the dir directory to the volumeRUN cp -r dir /vol# Remove the dir directory from the imageRUN rm -rf dir
Line 3–7: This will create the directory dir in the first layer, and then copy it to the volume. 
Line 10: The rm -rf dir command will remove the dir directory from the image.
Note: The deleted directory will still be accessible from the container, but it will not be part of the docker image.
Free Resources