How to remove directories and files in another layer using Docker
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.
Deleting the directory
Let's say that you have the following Dockerfile:
FROM alpineRUN mkdir dirRUN wget http://google.comRUN rm -r dir
Explanation
Line 3: This will create the directory
dirin the first layer.Line 4: The
wgetcommand will download the Google home page to thedirdirectory.Line 5: The
rm -r dircommand will try to remove thedirdirectory 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.
Use the 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
Explanation
Line 3–4: This will create the directory
dirin the first layer, and then change the current working directory todir.Line 5: The
wgetcommand will download the Google home page to thedirdirectory.Line 7: The
lscommand will list the contents of the current working directory, which will include thedirdirectory.Line 8: The
rm -r dircommand will remove thedirdirectory from the previous layer.
Use the 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
Explanation
Line 3–7: This will create the directory
dirin the first layer, and then copy it to the volume.Line 10: The
rm -rf dircommand will remove thedirdirectory 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