Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • DevOps Lifecycle
  • DevOps Roadmap
  • Docker Tutorial
  • Kubernetes Tutorials
  • Amazon Web Services [AWS] Tutorial
  • AZURE Tutorials
  • GCP Tutorials
  • Docker Cheat sheet
  • Kubernetes cheat sheet
  • AWS interview questions
  • Docker Interview Questions
  • Ansible Interview Questions
  • Jenkins Interview Questions
Open In App
Next Article:
Kubernetes - Images
Next article icon

Kubernetes - Kubectl Commands

Last Updated : 06 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Pre-requisites: Kubernetes 

The Kubernetes command-line tool, kubectl, allows you to run commands against Kubernetes clusters. You can use kubectl to deploy applications, inspect and manage cluster resources, and view logs. Some basic Kubectl commands in a Kubernetes cluster are as follows:

kubectl Commands 

The most popular kubectl commands and flags are listed below.

1. Common Commands 

Name 

Commands

Run a two-replica nginx deployment 

kubectl run my-nginx --image=nginx --replicas=5 --port=80

Run and expose the Nginx pod

kubectl run my-nginx --restart=Never --image=nginx --port=80 --expose

Run nginx deployment and expose it 

kubectl run my-nginx --image=nginx --port=80 --expose

List of nodes and pods

kubectl get pod -o wide 

List all of them.

kubectl get all --all-namespaces

Get every service

kubectl get service --all-namespaces

Show labeled nodes

kubectl get nodes --show-labels

Using a dry run, verify the yaml file

kubectl create --dry-run --validate -f pod-GFG.yaml 

2. Check Performance

NameCommand
learn about node resource usekubectl top node
Obtain pod resource use.kubectl top pod 
Get the resource utilization for the specified pod.kubectl top <podname> --containers
List each container's resource usage.kubectl top pod --all-namespaces --containers=true 

3. Label & Annontation

NameCommands
By label, sort the podskubectl get pods -l owner=gfg
Add a label by hand to a pod. kubectl label pods <podname> owner=gfg
Remove labelkubectl label pods <podname> owner- GFG

4.  Secrets 

NameCommands
List secretskubectl get secrets --all-namespaces
Obtain a certain hidden field of sceret. kubectl get secret GFG-cluster-kubeconfig

5. Service

NameCommands
List all serviceskubectl get services
List service endpointskubectl get endpoints
Get service detailkubectl get service <servicename> -o yaml

6. Volumes & Volume Claims

NameCommands
List storage classkubectl get storageclass 
Check the mounted volumeskubectl exec storage<nameofpv>
Check to persist volumekubectl describe <nameofpv>

Kubectl apply

We can update or apply the configuration to a cluster with the aid of "kubectl apply". With the help of the apply command, Kubernetes resources can be modified and created using a configuration file or a collection of configurations from a directory. 

Creating objects: The basic syntax of "kubectl apply"

kubectl apply -f <filename.yaml> 

Viewing and Finding Resources

These commands are used to show all the resources. It works like a READ operation. It is used to view resources like nodes, deployments, services, config maps, etc. 

$ kubectl get <resource>
  • Getting all Resources: The "kubectl get all" command enables us to view all of the cluster's resource
Getting all Resources
 
  • Getting  Nodes: The number of available nodes in the cluster will be displayed by "Kubectl get nodes". 
Getting  Nodes
 
  • Getting Pods: "Kubectl get pod" can be used to find out how many pods are scheduled in the cluster.
Getting Pods
 
  • Getting Services: "Kubectl get service" can be used to list the services that have been created in the cluster.
Getting Services
 

Creating Resources

These commands are used to create resources like deployments, services, secrets, config maps, etc.

$ kubectl create <resource_type> <resource_name> OPTIONS
  • Creating Deployment: The command creates a deployment named nginx-depl using the image Nginx.
Creating Deployment
 
  • Creating service: The command in the creates a service of type node port named nginx and it is exposed on port 80 of the local machine
Creating service
 

Editing Resources

After running the command below you can update the resource configuration file and if there are any changes the resource will be updated according to it.

kubectl edit <resource_type> <resource_name>
  • Updating Deployment: The command in the below output opens a Vim-like editor in the terminal to edit the Nginx-deal deployment config file.
Updating Deployment
 
  • Updating Service: The command opens a vim-like editor in the terminal to edit the Nginx service config file.
Updating Service
 

Deleting Resources

These commands are used to delete resources like deployments, services, config maps, pods, secrets, etc. You can choose a particular resource name of a resource type or you can also delete all resources of a resource type by specifying --all flag

kubectl delete <resource_type> <resource_name> | --all
  • Deleting Deployment: The command deletes a deployment named nginx-depl.
Deleting Deployment
 
  • Deleting Service: The command deletes a service named Nginx.
Deleting Service
 

Using Configuration File for CRUD

These commands are used to use YAML configuration files for CRUD operations in a cluster.

  • Applying a Config file: The command creates the resource if it does not exist or updates it if it already exists according to the configuration in the YAML file mentioned after the -f flag.
$ kubectl apply -f [file-name]
Applying a Config file
 
  • Deleting using Config file: The command deletes the resource that was created using the YAML config file mentioned after the -f flag/ 
$ kubectl delete -f [file-name]
Deleting using Config file
 

Interacting with running Pods

  • Viewing Logs of a Pod: The command shows the logs of the pod mentioned once the pod started.
$ kubectl logs [pod-name]
Viewing Logs of a Pod
 
  • Get an Interactive terminal for a pod: The command starts an interactive terminal of the Nginx pod so that we can control the pod directly through its terminal.
$ kubectl exec -it [pod-name] -- bin/bash
Get an Interactive terminal for a pod
 
  • Get info about a Resource: The command gives details about the nginx deployment
$ kubectl describe <resource_type> [resource-name]
Get info about a Resource

Copying Files and Directories to and from Containers

With the help of the "kubectl cp" command, we can copy files from host to container and vice versa.

The basic syntax of "kubectl  cp"

kubectl cp <host path pod name:container path> 

This command will only function if the "tar" command in the container images is present or the command failed to run. 

Updating Resources

The "kubectl get rs" command allows us to check the list of deployments, To update them, look up the revision history of prior deployments, and roll back to a specific revision if necessary. Using the following commands. 

kubectl rollout <history> , <undo> , <status>, <restart> 

Next Article
Kubernetes - Images

I

ishankhandelwals
Improve
Article Tags :
  • Technical Scripter
  • Kubernetes
  • DevOps
  • Technical Scripter 2022
  • Kubernetes-Basics

Similar Reads

    Kubernetes - Kubectl
    Kubectl is a command-line software tool that is used to run commands in command-line mode against the Kubernetes Cluster. Kubectl runs the commands in the command line, Behind the scenes it authenticates with the master node of Kubernetes Cluster with API calls and performs the operations on Kuberne
    12 min read
    Kubernetes - Kubectl Delete
    Kubernetes is an open-source Container Management tool that automates container deployment, container scaling, descaling, and container load balancing (also called a container orchestration tool). It is written in Golang and has a huge community because it was first developed by Google and later don
    8 min read
    Kubectl Command Cheat Sheet
    If you are inspired to become a DevOps (Devlopment+Operations)'s Engineer and start your journey as a beginner, or if you're a professional looking to refresh your DevOps knowledge or transition into DevOps, or even if you're a learning geek seeking to expand your knowledge base, then you landed to
    10 min read
    What is Kubelet in Kubernetes?
    A Kubelet in Kubernetes is a crucial component of the primary node agent that runs on each node. It assists with container management and orchestration within a Kubernetes cluster. Kubelet supports communication between the Kubernetes control plane and individual nodes and it also enables the effici
    4 min read
    Kubernetes - Images
    Pre-requisite:- Kubernetes A container image is used to represent binary data that is being used to encapsulate an application and all its software dependencies. Container images can be represented as executable software bundles that run standalone and make very defined assumptions about their runti
    3 min read
    Kubernetes - Kubectl Create and Kubectl Apply
    Kubernetes is an open-source Container Orchestrating software platform that is widely used in modern application deployment and management. It comes up with many internal resources to manage the other working nodes Organizing as a Cluster facilitates seamless automatic scaling, and deployment update
    8 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences