Kubernetes – Commands

Getting Started

CommandExplanation
minikube start –driver=virtualboxIf you are not using Docker Desktop, minikube can help setup a cluster with Virtualbox as driver
kubectl run hello-minikube –image=nginxRuns a Pod named hello-minikube with a nginx image.
kubectl cluster-infoDisplays cluster information, including API server and core services URLs.
kubectl run nginx –image=nginx –dry-run=client -o yaml > nginx.yamlGenerates a YAML configuration for a pad using nginx image without actually creating it in the cluster and saves the generated yaml file to nginx.yaml. –dry-run=client option simulates the command locally without sending it to the API Server. Useful for testing and generating configuration files.
kubectl run nginx –image nginx -n mynamespaceRuns a pod named ‘nginx’ in the ‘mynamespace’ namespace.
kubectl get events -o wideLists events across the cluster with additional details.
kubectl get allLists all resources in the current namespace
kubectl get all -ALists all resources across all namespaces.
kubectl get all –selector app=web-appLists all resources labeled with app=web-app
kubectl port-forward –helpDisplays help for the port-forward command.
kubectl port-forward pod/mypod 8888:5000Forwards local port 8888 to port 5000 on mypod
kubectl exec -it ubuntu –bashOpens an interactive Bash session in the ubuntu Pod
kubectl exec -it mypod -c sidecar –touch /tmp/crashCreates a file /tmp/crash in the sidecar container of mypod
kubectl explain pod.spec.restartPolicyProvides documentation for the restartPolicy field in the Pod spec
kubectl api-resourcesTo find out shortnames, namespaced or not and kind of resources. Retrieve list of all available API groups in a k8 cluster.

Nodes & Node Management

CommandExplanation
kubectl get nodesLists all nodes in current namespace
kubectl get nodes -o wideLists nodes with additional details like IP Addresses and roles
kubectl get node <NODE_NAME> –show-labelsView labels for a specific node
kubectl drain <NODE_NAME> –delete-emptydir-data –ignore-daemonsetsPrepares a node for maintenance by evicting pods
kubectl cordon control-planeMarks the control-plane node as unschedulable
kubectl uncordon node-nameMark a previously cordoned node as schedulable again.
kubectl taint nodes node1 role=frontend:PreferNoScheduleApplies a taint to a node to control Pod scheduling.
kubectl taint nodes node1 node2 dedicated=example:NoExecuteCan taint multiple nodes at once

Pods

CommandExplanation
kubectl get podsLists all nodes in the cluster with basic information
kubectl get pods -o wideLists nodes with additional information like IP Addresses and Node placement
kubectl get pods -n mynamespaceLists all pods in the given namespace
kubectl get pods –watchWatch all pods in the default namespace
kubectl get pods –field-selector=status.phase=Runningretrieves pods with a status of ‘Running’. Can be combined with label selectors also.
kubectl describe pod nginxShows detailed information about the pod named ‘nginx’
kubectl create -f pod-definition.ymlCreates a resource (pod) from the yaml file.
kubectl apply -f pod-definition.ymlApply changes from the yaml file to the existing resources.
kubectl delete pod mypodnameDeletes the Pod named mypodname.
kubectl delete pod/nginx pod/ubuntu –nowImmediately deletes the nginx and ubuntu Pods.
kubectl delete -f nginx.yamlDeletes resources defined in nginx.yaml
kubectl create pdb nginx –selector=app=nginx –min-available=2Creates a pod disruption budget to ensure at least two nginx pods remain available

Replicas

kubectl get replicationcontrollerLists all replication controllers in the namespace.
kubectl get replicasetsLists all replica sets in the namespace.
kubectl describe replicaset myapp-replicasetDisplays details about myapp-replicaset
kubectl edit replicaset myapp-replicasetOpens an editor to modify myapp-replicaset.
kubectl replace -f replicaset-definition.ymlReplaces the existing ReplicaSet with the definition in replicaset-definition.yml
kubectl scale -f replicaset-definition.yml –replicas=6Scales the ReplicaSet defined in replicaset-definition.yml to 6 replicas.
kubectl scale replicaset myapp-replicaset –replicas=6Scales the myapp-replicaset to 6 replicas
kubectl scale deployment/nginx –replicas=6; watch kubectl get pods -o wideScales the nginx Deployment to 6 replicas and monitors the Pod status.
kubectl delete replicaset myapp-replicasetDeletes the ReplicaSet named myapp-replicaset

Deployments

kubectl create -f deployment-definition.ymlCreates resources defined in deployment-definition.yml
kubectl create -f deployment-definition.yml –recordCreates resources while recording the changes.
kubectl create deployment –image=nginx nginxCreates a Deployment named nginx with the nginx image
kubectl get deploymentsLists all Deployments in the namespace.
kubectl rollout status deployment/myapp-deploymentChecks the rollout status of myapp-deployment.
kubectl rollout history deployment/myapp-deploymentShows the rollout history of myapp-deployment.
kubectl rollout undo deployment/myapp-deploymentRolls back myapp-deployment to the previous revision
kubectl set image deployment/myapp-deployment nginx=nginx:1.9.1Updates the image for nginx container in myapp-deployment to nginx:1.9.1
kubectl annotate deployment/nginx kubernetes.io/change-cause=”initial deployment”Adds a change-cause annotation to the nginx Deployment.
kubectl expose deployment nginx –port 80Exposes the nginx Deployment on port 80.
kubectl delete deployment myapp-deploymentDeletes the myapp-deployment Deployment.

Namespaces

kubectl create -f namespace-dev.ymlCreates a namespace using namespace-dev.yml.
kubectl create namespace devCreates a namespace named dev.
kubectl get namespaces (or) kubectl get nsLists all namespaces
kubectl delete namespace/mynamespace –nowImmediately deletes the mynamespace namespace.

Services & Endpoints

kubectl get endpointsLists all service endpoints in the namespace
kubectl get servicesLists all services in the namespace
kubectl expose deployment nginx –type=NodePortExposes the nginx deployment as a NodePort service
kubectl expose deployment nginx –type=LoadBalancer –port 8080 –target-port 80Exposes nginx on an external LoadBalancer.
kubectl create service externalname my-service –external-name nginx-red.default.svc.cluster.localCreates an ExternalName service that points to a DNS address.
kubectl delete service/nginxDeletes the nginx service
kubectl delete service/nginix-blue service/nginx-red service/my-serviceDelete multiple services
kubectl get serviceaccountLists all service accounts in the namespace.
kubectl create serviceaccount dashboard-saCreates a service account named dashboard-sa.
kubectl describe serviceaccount dashboard-saShows details of the dashboard-sa service account.

Roles & Permissions

kubectl get clusterrolebindings -o wideLists cluster role bindings with detailed output.
kubectl describe ClusterRole/cluster-adminShows details for the cluster-admin role.
kubectl create clusterrole cluster-superuser1 –verb=’*’ –resource=’*’Creates a cluster role with full permission on all resources
kubectl create clusterrolebinding cluster-superuser1 –clusterrole=cluster-superuser1 –group=cluster-superusers1Binds cluster role to a group
kubectl auth can-i ‘*‘ ‘*’Checks if the user has permissions for all actions on all resources.
kubectl auth can-i ‘*’ ‘*’ –as-group=”cluster-superusers1″ –as=”msd”Checks if user ‘msd‘ has full permissions under the specified group
kubectl get rolesLists all roles in the namespace.
kubectl get rolebindingsLists all role bindings in the namespace.
kubectl describe role <ROLE_NAME>Shows details of the specified role.

Daemonsets

kubectl get daemonsetsLists all DaemonSets in the namespace.
kubectl describe daemonsets monitoring-daemonDisplays details of the monitoring-daemon DaemonSet.

Jobs

kubectl create job calculatepi –image=perl:5.34.0 — “perl” “-Mbignum=bpi” “print bpi(2000)”Creates a job to calculate pi using a Perl script.
kubectl delete job calculatepiDeletes the calculatepi job.
kubectl delete job calculatepi –cascade=falseDeletes calculatepi without cascading deletion.
kubectl delete jobs –all -nDeletes all jobs in the specified namespace.
kubectl delete job myjob1 –grace-period=0 –forceForcibly deletes myjob1 without waiting.

Storage & Persistent Volume

kubectl get storageclassLists all storage classes
kubectl get persistentvolumeLiss all persistent volumes
kubectl get persistentvolumeclaimLists all persistent volume claims.

Labels, Configs & Sectrets

kubectl config set-context $(kubectl config current-context) –namespace=prodSets the default namespace to prod for the current context.
kubectl config use-contextSwitches to a specified context.
kubectl config viewDisplays the Kubernetes configuration settings.
kubectl config view –kubeconfig=/home/user/custom-config.yamlViews a specific kubeconfig file.
kubectl config view –rawDisplays the full, raw configuration
kubectl config set-context –current –namespace=mynamespaceSets the default namespace for the current context to mynamespace.
kubectl label namespace default istio-injection=enabledAdds the istio-injection=enabled label to the default namespace.
kubectl label nodes node-name label-key=label-valueAdds a label to a node
kubectl create configmap myconfigmap –from-literal=COLOR=red –from-literal=City=chennaiCreates a configmap from literal values.
kubectl create configmap myconfigmap –from-env-file=config.propertiesCreates a configmap from an env file
kubectl create secret docker-registry regcred –docker-server=private-registry.io –docker-username=userCreates a docker registry secret
kubectl create token dashboard-saGenerates a token for dashboard-sa
kubectl describe secret dashboard-sa-token-kbbdmShow details of token

Logs

CommandExplanation
kubectl logs pod/nginxRetrieves logs from the pod named ‘nginx’ in the current namespace
kubectl logs pod/nginx -c my-container -fIf your pod has multiple containers, specify the container name with -c. The -f flag (follow) streams the logs in real time.
kubectl logs pod/nginx -c my-container -p-p flag retrieves logs from previous instance of the container if it has restarted. Useful in debugging a crashed container.
kubectl logs pod/nginx –all-containers=trueGet logs from all containers
kubectl logs -l app=mywebappRetrieves logs from all pods with label app=mywebapp.
kubectl logs deployment/nginxRetrieves logs from one of the pods in the ‘nginx’ deployment. Shows logs from a single pod only.

Scaling

kubectl get hpaLists all horizontal pod autoscalers in the namespace
kubectl scale deployment my-deployment –replicas=5Scale a deployment
kubectl scale replicaset my-replicaset –replicas=3Scale a replicaset
kubectl scale statefulset my-statefulset –replicas=4Scale a statefulset
kubectl autoscale deployment my-deployment –min=2 –max=10 –cpu-percent=80Autoscale a deployment based on CPU usage
Scroll to Top