Quantcast
Channel: Active questions tagged dockerfile - DevOps Stack Exchange
Viewing all articles
Browse latest Browse all 136

How to remove directories and files in another layer using Docker? [duplicate]

$
0
0

Why this question?

The reason for posting this Q&A is that sometimes certain software is required to compile software in a docker image. Once compiled, these packages are superfluous and should be removed in order to reduce the image size. In some cases images that were more than 1.5GB where reduced to less than 300MB. The following use case does not represent a real world scenario, but provides an example of this use case.

Attempts to solve the issue

It works to remove a directory when the remove command is defined in the same layer as the creation of the folder:

FROM alpineRUN mkdir dir && cd dir && wget http://google.com && rm -rf dir

This results in:

user@host$ docker build -t dir .Sending build context to Docker daemon 1.336 MBStep 1/2 : FROM alpine ---> 4a415e366388Step 2/2 : RUN mkdir dir && cd dir && wget http://google.com && rm -rf dir ---> Using cache ---> c283805e687fSuccessfully built c283805e687f

When the aim is to remove the directory in another layer, this fails:

FROM alpineRUN mkdir dir && cd dir && wget http://google.comRUN rm -r dir

And this fails:

FROM alpineRUN mkdir dir && cd dir && wget http://google.comRUN rm -rf dir

Another attempt was using workdir:

FROM alpineRUN mkdir dirWORKDIR dirRUN wget http://google.comWORKDIR /RUN lsRUN rm -r dir

Building the image resulted in:

Sending build context to Docker daemon 2.048 kBStep 1/7 : FROM alpine ---> 4a415e366388Step 2/7 : RUN mkdir dir ---> Using cache ---> aed5c75218cbStep 3/7 : WORKDIR dir ---> Using cache ---> 715de09e7e08Step 4/7 : RUN wget http://google.com ---> Using cache ---> c07bfb3e1133Step 5/7 : WORKDIR / ---> Using cache ---> c6de86d0191aStep 6/7 : RUN ls ---> Using cache ---> 9567593cce39Step 7/7 : RUN rm -r dir ---> Running in 7fe7b28294bfrm: can't remove 'dir': Directory not emptyThe command '/bin/sh -c rm -r dir' returned a non-zero code: 1

Viewing all articles
Browse latest Browse all 136

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>