How can I prevent Docker from removing intermediate containers when executing RUN command?

Viewed 5935

The error I'm experiencing is that I want to execute the command "change directory" in my Docker machine, but every time I execute RUN instruction in my Dockerfile, it deletes the actual container (intermediate container).

DOCKERFILE

enter image description here

This happens when I execute the Dockerfile from above

enter image description here

How can I prevent Docker from doing that?

3 Answers

The current paths are different for Dockerfile and RUN (inside container).

Each RUN command starts from the Dockerfile path (e. g. '/').

When you do RUN cd /app, the "inside path" changes, but not the "Dockerfile path". The next RUN command will again be run at '/'.

To change the "Dockerfile path", use WORKDIR (see reference), for example WORKDIR /opt/firefox.

The alternative would be chaining the executed RUN commands, as EvgeniySharapov pointed out: RUN cd opt; ls; cd firefox; ls

on multiple lines:

RUN cd opt; \
    ls; \
    cd firefox; \
    ls

(To clarify: It doesn't matter that Docker removes intermediate containers, that is not the problem in this case.)

docker build --rm=false

Remove intermediate containers after a successful build (default true)

When you use docker build --no-cache this will delete intermediate containers when you build an image. This may affect building times when you run build multiple times. Alternatively you can choose to put multiple shell commands into one shell command using \ and then use it as a RUN argument. Mote tips could be found here

Related