Run multiple commands in kubernetes

This article will describe how to run multiple commands on container startup phase in kubernetes. Kubernetes provides several ways to run multiple command for a container, such as command parameter in container spec, or provide an entry point shell. bellow is an example for demonstrate how to run multiple commands in kubernetes.

Using command parameter

apiVersion: v1
kind: Pod
metadata:
  labels:
    run: busybox
  name: busybox
spec:
  containers:
  - command:
    - /bin/sh
    - -c
    - |
      echo "running below scripts"
      i=0; 
      while true; 
      do 
        echo "$i: $(date)"; 
        i=$((i+1)); 
        sleep 1; 
      done
    name: busybox
    image: busybox

Also, you can use command and args parameters, for better readablity, yaml scalar block(>-) is prefered:

apiVersion: v1
kind: Pod
metadata:
  name: hello-world
spec:  # specification of the pod’s contents
  restartPolicy: Never
  containers:
  - name: hello
    image: "ubuntu:14.04"
    command: ["/bin/sh"]
    args:
      - -c
      - >-
          command1 arg1 arg2 &&
          command2 arg3 &&
          command3 arg4

The third way, you can put your commands in a bash shell as a configmap, and mount that file in container,

---
apiVersion: v1
kind: ConfigMap
metadata:
  name: my-configmap
data:
  entrypoint.sh: |-
    #!/bin/bash
    echo "Do this"

    echo "Do that"
---
apiVersion: v1
kind: Pod
metadata:
  name: my-pod
spec:
  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

Leave a Reply

Your email address will not be published. Required fields are marked *