Commands and Arguments in Docker

CMD and ENTRYPOINT in Dockerfile

The CMD instruction says which command is to be run when the container starts. This is the command to be run while the container is alive. When this command finishes or crashes, the container finishes.

Example:

# image name: ubuntu-sleeper
FROM ubuntu

# sleep for 5 seconds
CMD sleep 5

It can be overwritten in the command line:

docker container run ubuntu-sleeper sleep 10
# command at startup: sleep 10

The CMD instruction also accepts an "array notation":

# CMD command param1 paramN

CMD ["command", "param1", "paramN"]

If you want your image to have always the same command, but let the user set an argument, use the ENTRYPOINT instruction:

# image name: ubuntu-sleeper
FROM ubuntu

ENTRYPOINT ["sleep"]

Now you can just pass the argument in the docker command:

docker container run ubuntu-sleeper 10
# command at startup: sleep 10

If you don't pass an argument, the resulting command is going to be sleep which generates an error.

You can also have the same command and a default argument:

# image name: ubuntu-sleeper
FROM ubuntu

ENTRYPOINT ["sleep"]

CMD ["5"]

This way you can use the default command or pass an argument to overwrite the default one:

docker container run ubuntu-sleeper
# command at startup: sleep 5

docker container run ubuntu-sleeper 10
# command at startup: sleep 10

And if you want to overwrite the entrypoint:

docker container run --entrypoint sleep2.0 ubuntu-sleeper 10
# command at startup: sleep2.0 10

command and args in Pod's definition

If you want to overwrite ENTRYPOINT and CMD in the Pod's definition file, use the command and args keys.

Example:

apiVersion: v1

kind: Pod

metadata:
  name: ubuntu-sleeper-pod

spec:
  containers:
    - name: ubuntu-sleeper
      image: ubuntu-sleeper
      
      # overwrites ENTRYPOINT
      command: ["sleep2.0"]
      
      # overwrites CMD
      args: ["10"]

Note: remember that CMD is NOT overwritten by the command key, but by args.