How to set multiple commands in one yaml file with Kubernetes? How to set multiple commands in one yaml file with Kubernetes? kubernetes kubernetes

How to set multiple commands in one yaml file with Kubernetes?


command: ["/bin/sh","-c"]args: ["command one; command two && command three"]

Explanation: The command ["/bin/sh", "-c"] says "run a shell, and execute the following instructions". The args are then passed as commands to the shell. In shell scripting a semicolon separates commands, and && conditionally runs the following command if the first succeed. In the above example, it always runs command one followed by command two, and only runs command three if command two succeeded.

Alternative: In many cases, some of the commands you want to run are probably setting up the final command to run. In this case, building your own Dockerfile is the way to go. Look at the RUN directive in particular.


My preference is to multiline the args, this is simplest and easiest to read. Also, the script can be changed without affecting the image, just need to restart the pod. For example, for a mysql dump, the container spec could be something like this:

containers:  - name: mysqldump    image: mysql    command: ["/bin/sh", "-c"]    args:      - echo starting;        ls -la /backups;        mysqldump --host=... -r /backups/file.sql db_name;        ls -la /backups;        echo done;    volumeMounts:      - ...

The reason this works is that yaml actually concatenates all the lines after the "-" into one, and sh runs one long string "echo starting; ls... ; echo done;".


If you're willing to use a Volume and a ConfigMap, you can mount ConfigMap data as a script, and then run that script:

---apiVersion: v1kind: ConfigMapmetadata:  name: my-configmapdata:  entrypoint.sh: |-    #!/bin/bash    echo "Do this"    echo "Do that"---apiVersion: v1kind: Podmetadata:  name: my-podspec:  containers:  - name: my-container    image: "ubuntu:14.04"    command:    - /bin/entrypoint.sh    volumeMounts:    - name: configmap-volume      mountPath: /bin/entrypoint.sh      readOnly: true      subPath: entrypoint.sh  volumes:  - name: configmap-volume    configMap:      defaultMode: 0700      name: my-configmap

This cleans up your pod spec a little and allows for more complex scripting.

$ kubectl logs my-podDo thisDo that