How to set multiple commands in one yaml file with Kubernetes

When working with Kubernetes, you may come across scenarios where you need to execute multiple commands within a container. This can be useful for various reasons, such as initializing the container with specific configurations, running setup scripts, or performing multiple tasks sequentially.

By default, a container in Kubernetes executes a single command specified by the CMD or ENTRYPOINT directive in the container image. However, there are situations where you may need to run multiple commands or execute a shell script with multiple steps.

Address the requirement

To set multiple commands in one YAML file with Kubernetes, you can use the following approaches:

Using the command and args fields:

  1. Create a YAML file with the following structure:

apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: busybox
command: ["/bin/sh","-c"]
args: ["command one; command two && command three"]

Or we can also use multi-line code in the in the args field as shown below:

apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: busybox
command: ["/bin/sh", "-c"]
args:
- echo "This is the first command";
sleep 1;
echo "This is the second command";
  1. Save the YAML file and apply it to your Kubernetes cluster.

kubectl apply -f my-pod.yaml
Command to save and apply yaml file to cluster
  1. The pod will start and execute the two commands in the args field.

Note: The command field in the YAML file specifies the command that will be executed when the pod starts. In this case, the command is /bin/sh -c, which tells the shell to execute the commands that are specified in the args field. The args field is a list of strings, and each string represents a command that will be executed.

Using a shell script:

Instead of specifying the commands directly in the YAML file, you can create a shell script file that contains the desired commands and then reference that script in the YAML file. Here's an example:

apiVersion: v1
kind: Pod
metadata:
name: my-pod
spec:
containers:
- name: my-container
image: my-image
command: ["/bin/sh"]
args: ["-c", "sh /path/to/my-script.sh"]

Note: In this example, we specify the shell script /path/to/my-script.sh as the argument to the /bin/sh command. The shell script file my-script.sh can contain multiple commands that you want to execute.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved