Kubernetes Commands and Actions
1. kubectl get
Retrieves and lists resources in the cluster.
- List Pods:
kubectl get pods
- List Services:
kubectl get services
- List Nodes:
kubectl get nodes
2. kubectl describe
Provides detailed information about a resource.
- Describe a Pod:
kubectl describe pod <pod-name>
- Describe a Service:
kubectl describe service <service-name>
3. kubectl create
Creates a new resource in the cluster.
- Create a Pod from a YAML file:
kubectl create -f pod.yaml
- Create a Deployment:
kubectl create deployment my-app --image=nginx
4. kubectl apply
Applies a configuration to a resource, either creating or updating it.
- Apply a Deployment YAML file:
kubectl apply -f deployment.yaml
5. kubectl delete
Deletes resources from the cluster.
- Delete a Pod:
kubectl delete pod <pod-name>
- Delete a Service:
kubectl delete service <service-name>
6. kubectl logs
Fetches logs from a container in a pod.
- Get Logs from a Pod:
kubectl logs <pod-name>
7. kubectl exec
Executes a command inside a container in a pod.
- Execute a Command Inside a Pod:
kubectl exec -it <pod-name> -- /bin/bash
8. kubectl scale
Scales a resource, such as a Deployment, ReplicaSet, or StatefulSet.
- Scale a Deployment:
kubectl scale deployment my-app --replicas=3
9. kubectl expose
Exposes a resource (like a Pod or Deployment) as a Service.
- Expose a Pod as a Service:
kubectl expose pod <pod-name> --port=80 --target-port=8080
10. kubectl port-forward
Forwards a local port to a port on a pod.
- Port Forward a Pod:
kubectl port-forward <pod-name> 8080:80
11. kubectl config
Manages your kubeconfig files and the current context.
- View Current Context:
kubectl config current-context
12. kubectl version
Displays the version of kubectl and the Kubernetes cluster.
- Check Version:
kubectl version
13. kubectl rollout
Manages the rollout of a deployment (used for updating and monitoring).
- Check Rollout Status:
kubectl rollout status deployment/my-app
- Rollback a Deployment:
kubectl rollout undo deployment/my-app
Example: Deploying a Sample Application
1. Create a Deployment for Nginx:
kubectl create deployment nginx --image=nginx
2. Expose the Deployment as a Service:
kubectl expose deployment nginx --port=80 --target-port=80 --type=NodePort
3. Scale the Deployment to 3 Replicas:
kubectl scale deployment nginx --replicas=3
4. Check the Status of the Deployment:
kubectl rollout status deployment/nginx
5. Port-forward to Access the Application Locally:
kubectl port-forward service/nginx 8080:80
6. Get the List of Pods:
kubectl get pods
7. View the Logs of One of the Pods:
kubectl logs <pod-name>
8. Check the Cluster Nodes:
kubectl get nodes
9. Delete the Deployment and Service:
kubectl delete deployment nginx
kubectl delete service nginx