kubernetes
Exam Tips

Exam Tips

Imperative Commands with dry-run

Use --dry-run=client to generate the YAML file for the resource without actually creating it.

# pod
kubectl run nginx --image=nginx --dry-run=client -o yaml
kubectl run nginx --image=nginx --port=80 --expose # expose the pod as a service
 
# deployment
kubectl create deployment --image=nginx nginx --dry-run=client -o yaml > sample-deployment.yaml
 
# expose pod as service
kubectl expose pod nginx --port=80 --name=nginx-service --type=NodePort --dry-run=client -o yaml
 
# service
# the type of service is clusterip
kubectl create service clusterip nginx --tcp=80:80 --dry-run=client -o yaml
kubectl create service nodeport nginx --tcp=80:80 --node-port=31080 --dry-run=client -o yaml

Format output with kubectl

For better readability, you can use this command kubectl [command] [TYPE] [NAME] -o <output_format> to format the output.

Commonly used output formats are:

  • -o json - Output a JSON formatted API object
  • -o name - Only display resource name
  • -o wide - Output in the plain-text format with any additional information
  • -o yaml - Output a YAML formatted API object
kubectl get svc -o wide

Edit a deployment

kubectl edit deployment <deployment-name> will automatically delete the existing deployment and create a new one with the changes.

Edit a pod

When you edit an existing pod, there are some specifications you cannot edit. For example,

  • spec.containers[*].image
  • spec.initContainers[*].image
  • spec.activeDeadlineSeconds
  • spec.tolerations

If you use this command kubectl edit pod <pod-name>, you cannot save the file after editing it, instead it will save the file with the changes in a temporary location.

So, in this case, we have multiple options to edit the pod:

  1. Delete and apply the temporary file

    kubectl delete pod <pod-name>
    kubectl apply -f <temporary-file>
  2. Save existing pod, edit it, delete existing, and apply the edited file

    kubectl get pod <pod-name> -o yaml > new-pod.yaml
    vi new-pod.yaml
    kubectl delete pod <pod-name>
    kubectl apply -f new-pod.yaml

Exec without enter the pod shell

kubectl exec <pod-name> -- <command>
kubectl exec <pod-name> -- ls /var/log

Enter the pod shell

kubectl exec -it <pod-name> -- <command>
kubectl exec -it <pod-name> -- /bin/bash
kubectl exec --stdin --tty <pod-name> -- /bin/bash

Delete the pod faster

kubectl delete pod/<pod-name> --force --grace-period=0