0
votes

I'm trying to understand how Dockerfile's RUN and CMD works.

From: https://docs.docker.com/engine/reference/builder/

The RUN instruction will execute any commands in a new layer on top of the current image and commit the results. The resulting committed image will be used for the next step in the Dockerfile.

The main purpose of a CMD is to provide defaults for an executing container.

And just to test if the RUN and CMD commands are executed from my Dockerfile, I have

RUN touch "RUN.s.txt"
CMD touch "CMD.s.txt"

None of those command are executed, otherwise I'll see those two files created. So what went wrong?

1
Can you show the output of docker build and docker run?John Kugelman

1 Answers

1
votes

You will not able to see your files, as your container dies when it creates the file.

Remember CMD execute the command when container started. so to check the created filed you need to change CMD.

FROM alpine
RUN touch "RUN.s.txt"
CMD touch "CMD.s.txt" && ls

CMD should be a long-running process to interact with the container, otherwise, the container will die as soon as it completes the execution of touch file.

with CMD touch "CMD.s.txt" && ls you will able to see created file previously with RUN touch "RUN.s.txt" and the file created by CMD.