Home > Software engineering >  Role of CMD["bash"] in Dockerfile
Role of CMD["bash"] in Dockerfile

Time:06-11

This is the Dockerfile of Docker Ubuntu official image:

FROM scratch
ADD ubuntu-focal-oci-amd64-root.tar.gz /
CMD ["bash"]

Can you please help me clarifying the following:

  1. What exactly CMD["bash"] does? I can see no difference by removing it (e.g. by adding in my local Dockerfile: CMD["echo", "hello"]) when starting a container.
  2. The equivalent shell form is CMD bash or CMD exec bash?
  3. If removing that completely, what is the equivalent docker exec command line?

I cannot find any reliable answer despite my thorough search...

CodePudding user response:

  1. When you create an image FROM scratch, among other things, it has an empty default command, as if you had written

    ENTRYPOINT []
    CMD []
    
  2. So CMD there gives some default command if you docker run ubuntu. Most images will in fact override that CMD with something to run the program built into the derived image.

  3. Since that CMD uses JSON-array syntax, there isn't directly a shell-syntax equivalent of it. The shell syntax automatically inserts a sh -c wrapper around whatever command you give it, so these two would be equivalent

    CMD bash
    CMD ["/bin/sh", "-c", "bash"]
    
  4. There would not be an equivalent docker exec command. docker exec is a debugging command that's not normally part of the "build and run an image" workflow. In particular, it does not use the ENTRYPOINT or CMD from the image at all.

  • Related