Sunday 12 July 2020

Kubernetes: Specify the command to run in pod definition file

You can specify the command to run in the Pod definition file itself.

 

helloWorldTerminalApp.yml
apiVersion: v1
kind: Pod
metadata:
  name: hello-world
  labels:
    app: hello-world
    author: krishna
    serviceType: terminal-app
spec:
  containers:
    - name: hello-world
      image: busybox
      command:
        - sleep 
        - "30"

Above command creates pod with the image busybox. I specify the command to run in ‘command:’ property.

 

Let’s create another Pod definition file, that prints something to console. So we can see what is happening via ‘kubectl logs’ command.

 

executeCommandPod.yml
apiVersion: v1
kind: Pod
metadata:
  name: execute-command-pod
  labels:
    app: hello-world
    author: krishna
    serviceType: terminal-app
spec:
  containers:
    - name: execute-command-container
      image: busybox
      command: ["/bin/sh"]
      args: ["-c", "while true; do echo 'Hello World'; sleep 5; done"]

As you see the definition file, I am just printing the message 'Hello World' to console for every 5 seconds.

 

Let’s create a Pod using the above definition file.
$kubectl create -f executeCommandPod.yml 
pod/execute-command-pod created

Wait until Pod is in Running state.

$kubectl get pods
NAME                  READY   STATUS    RESTARTS   AGE
execute-command-pod   1/1     Running   0          9s

Use ‘kubectl logs’ command to see the output of the command that we gave in the definition file.

$kubectl logs execute-command-pod
Hello World
Hello World

Wait for 5 seconds and re-execute the logs command, you will see another ‘Hello World’ message.

$kubectl logs execute-command-pod
Hello World
Hello World
Hello World

You can delete the pod by executing the below command.

kubectl delete pods execute-command-pod

$kubectl delete pods execute-command-pod
pod "execute-command-pod" deleted

Previous                                                    Next                                                    Home

No comments:

Post a Comment