[Kubernetes] Commands

When you run a container in a pod, you might want to run a command at the start-up. The process consists of 2 stages – at the container (docker) level and at the Kubernetes level.

Docker – Commands and Entry points

CMD directive

The “CMD” instruction can be one of three forms:

  • Executable form – Preferred
    • CMD [“executable”, “param1”, “param2”]
  • Default parameters form to ENTRYPOINT
    • CMD [“param1”, “param2”]
  • Shell form
    • CMD executable parm1 parm2

Please make sure the differences of each form.

  • In the shell form, the CMD will execute in “/bin/sh -c“.
  • In the array form, the CMD will not be invoked in a command shell.
FROM ubuntu
CMD echo "Hello World"
FROM ubuntu
CMD ["sh", "-c", "echo 'Hello World'"]

ENTRYPOINT directive

The ENTRYPOINT instruction allows you to configure a container to run an executable.

  • Executable form – Preferred
    • ENTRYPOINT [“executable”, “param1”, “param2”]
  • Shell form
    • ENTRYPOINT executable parm1 parm2
FROM ubuntu
ENTRYPOINT ["sh", "-c", "echo 'Hello World'"]

ENTRYPOINT + CMD

ENTRYPOINT and CMD look quite similar and redundant. The power of the configuration comes when both directives are used at the same time.

  • ENTRYPOINT: specifies the executable and stable default parameters
  • CMD: specifies additional default parameters but might be replaced at runtime

[Note] You need to use only the array form here.

A container will run the combined command ENTRYPOINT + CMD.

Here are the rules of how ENTRYPOINT and CMD interact together.

  • Dockerfile should specify at least one of CMD or ENTRYPOINT.
  • ENTRYPOINT should be defined when using the container as an executable.
  • CMD should be used as a way of defining default arguments for an ENTRYPOINT command or for executing an ad-hoc command in a container.
  • CMD will be overridden when running the container with alternative arguments.
No ENTRYPOINTENTRYPOINT [“exec1”, “p1”]
No CMDerrorexec1 p1
CMD [“exec2”, “p2”]exec2 p2
CMD [“p2”]exec1 p1 p2
FROM ubuntu
ENTRYPOINT ["sh", "-c"]
CMD ["echo 'Hello World'"]

When you run the image above with arguments, CMD parameters will be replaced.

docker run my-ubuntu sleep 10

Kubernetes – Commands

You can specify the docker CMD argument or ENTRYPOINT argument in the Kubernetes definition file.

  • ENTRYPOINT = “spec.containers.command
  • CMD =”spec.containers.args
apiVersion: v1
kind: Pod
metadata:
  name: ubuntu-pod
spec:
  containers:
  - name: ubuntu-container
    image: my-ubuntu
    command: ["sh", "-c", "echo"]
    args: ["Hello World"]

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s