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 Docker daemon A persistent background process that manages Docker images, containers, networks, and storage volumes. creates a new layer for each command that you 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 alpine
RUN mkdir dir
RUN wget http://google.com
RUN rm -r dir

Explanation

  • 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 dir command will fail because the directory dir is not present in the current layer. The directory dir was 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 alpine
RUN mkdir dir
WORKDIR dir
RUN wget http://google.com
WORKDIR /
RUN ls
RUN rm -r dir

Explanation

  • 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.

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 alpine
RUN mkdir dir
VOLUME /vol
# Copy the dir directory to the volume
RUN cp -r dir /vol
# Remove the dir directory from the image
RUN rm -rf dir

Explanation

  • 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

Copyright ©2025 Educative, Inc. All rights reserved