kubernetes common commands

kubectl common examples

View class commands

# Get node and service version information
kubectl get nodes
# Get node and service version information and view additional information
kubectl get nodes -o wide

# Get the pod information. The default namespace is default
kubectl get pod
# Get the pod information, default namespace by default, and view additional information (such as the IP address of the pod and the node on which it runs)
kubectl get pod -o wide
# Gets the pod for the specified namespace
kubectl get pod -n kube-system
# Gets the specified pod in the specified namespace
kubectl get pod -n kube-system podName
# Gets the pod for all namespaces
kubectl get pod -A
# View the details of the pod and display it in yaml format or json format
kubectl get pods -o yaml
kubectl get pods -o json

# View the tag information of pod
kubectl get pod -A --show-labels
# Query the pod according to the Selector (label query)
kubectl get pod -A --selector="k8s-app=kube-dns"

# View environment variables for running pod
kubectl exec podName env
# View the log of the specified pod
kubectl logs -f --tail 500 -n kube-system kube-apiserver-k8s-master

# View service information for all namespaces
kubectl get svc -A
# View the service information of the specified namespace
kubectl get svc -n kube-system

# View component statuses information
kubectl get cs
# View all configmaps information
kubectl get cm -A
# View all service accounts information
kubectl get sa -A
# View all daemonsets information
kubectl get ds -A
# View all deployments information
kubectl get deploy -A
# View all replicasets information
kubectl get rs -A
# View all statefulsets information
kubectl get sts -A
# View all jobs information
kubectl get jobs -A
# View all ingresses information
kubectl get ing -A
# See what namespaces are available
kubectl get ns

# View the description of the pod
kubectl describe pod podName
kubectl describe pod -n kube-system kube-apiserver-k8s-master
# View the description of the specified deploy in the specified namespace
kubectl describe deploy -n kube-system coredns

# View the resource usage of node or pod
# heapster or metrics server support is required
kubectl top node
kubectl top pod

# View cluster information
kubectl cluster-info   or  kubectl cluster-info dump
# View the information of each component [172.16.1.110 is the master machine]
kubectl -s https://172.16.1.110:6443 get componentstatuses

Operation class Command

# Create resource
kubectl create -f xxx.yaml
# Application resources
kubectl apply -f xxx.yaml
# Application resources, all in this directory yaml, .yml, or json files will be used
kubectl apply -f <directory>
# Create test namespace
kubectl create namespace test

# Delete resource
kubectl delete -f xxx.yaml
kubectl delete -f <directory>
# Delete the specified pod
kubectl delete pod podName
# Deletes the specified pod for the specified namespace
kubectl delete pod -n test podName
# Delete other resources
kubectl delete svc svcName
kubectl delete deploy deployName
kubectl delete ns nsName
# Force delete
kubectl delete pod podName -n nsName --grace-period=0 --force
kubectl delete pod podName -n nsName --grace-period=1
kubectl delete pod podName -n nsName --now

# Edit resources
kubectl edit pod podName

Advanced command operation

# kubectl exec: enter the container started by pod
kubectl exec -it podName -n nsName /bin/sh    #Enter container
kubectl exec -it podName -n nsName /bin/bash  #Enter container

# kubectl label: add label value
kubectl label nodes k8s-node01 zone=north  #Adds a label to the specified node
kubectl label nodes k8s-node01 zone-       #Deletes a label for the specified node
kubectl label pod podName -n nsName role-name=test    #Label the specified pod
kubectl label pod podName -n nsName role-name=dev --overwrite  #Modify label value
kubectl label pod podName -n nsName role-name-        #Delete label

# Kubectl rolling upgrade; Via kubectl apply - F myapp-deployment-v1 Yaml start deploy
kubectl apply -f myapp-deployment-v2.yaml     #Rolling upgrade through profile
kubectl set image deploy/myapp-deployment myapp="registry.cn-beijing.aliyuncs.com/google_registry/myapp:v3"   #Scrolling through commands
kubectl rollout undo deploy/myapp-deployment perhaps kubectl rollout undo deploy myapp-deployment    #The pod rolls back to the previous version
kubectl rollout undo deploy/myapp-deployment --to-revision=2  #Rollback to the specified historical version

# kubectl scale: dynamic scaling
kubectl scale deploy myapp-deployment --replicas=5  # Dynamic scaling
kubectl scale --replicas=8 -f myapp-deployment-v2.yaml  #Dynamic scaling [scaling according to resource type and name, other configurations such as different image versions will not take effect]

The yaml file of deploy involved in rolling update and dynamic scaling above

[root@k8s-master deploy]# cat myapp-deployment-v1.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
    app: myapp
spec:
  replicas: 10
  # Focus on this field
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: registry.cn-beijing.aliyuncs.com/google_registry/myapp:v1
        ports:
        - containerPort: 80

[root@k8s-master deploy]#
[root@k8s-master deploy]# cat myapp-deployment-v2.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp-deployment
  labels:
    app: myapp
spec:
  replicas: 10
  # Focus on this field
  selector:
    matchLabels:
      app: myapp
  template:
    metadata:
      labels:
        app: myapp
    spec:
      containers:
      - name: myapp
        image: registry.cn-beijing.aliyuncs.com/google_registry/myapp:v2
        ports:
        - containerPort: 80

kubectl syntax

kubectl [command] [TYPE] [NAME] [flags]

Official website address: https://kubernetes.io/docs/reference/kubectl/overview/ 
kubectl flags: https://kubernetes.io/docs/reference/kubectl/kubectl/

explain:

1. command: Specifies the operation to be performed on one or more resources. For example: create, get, describe, delete, apply, etc

2. TYPE: Specifies the resource TYPE (such as pod, node, services, deployments, etc.). Resource types are case sensitive and can specify singular, plural or abbreviation forms. For example, the following command produces the same output:

1 kubectl get pod  -n kubernetes-dashboard
2 kubectl get pods -n kubernetes-dashboard
3 kubectl get po   -n kubernetes-dashboard

3. NAME: Specifies the NAME of the resource. Names are case sensitive. If the namespace is omitted, the details of the default namespace resources or the prompt: No resources found in default namespace.

# Example:
[root@k8s-master ~]# kubectl get pods
No resources found in default namespace.
[root@k8s-master ~]# kubectl get pods --all-namespaces  # Or kubectl get pods --A
NAMESPACE              NAME                                         READY   STATUS    RESTARTS   AGE
kube-system            coredns-6955765f44-c9zfh                     1/1     Running   8          6d7h
kube-system            coredns-6955765f44-lrz5q                     1/1     Running   8          6d7h
kube-system            etcd-k8s-master                              1/1     Running   9          6d7h
kube-system            kube-apiserver-k8s-master                    1/1     Running   9          6d7h
kube-system            kube-controller-manager-k8s-master           1/1     Running   8          6d7h
kube-system            kube-flannel-ds-amd64-dngrk                  1/1     Running   13         6d7h
kube-system            kube-flannel-ds-amd64-h4sn6                  1/1     Running   13         6d6h
kube-system            kube-flannel-ds-amd64-m92wp                  1/1     Running   11         6d6h
kube-system            kube-proxy-28dwj                             1/1     Running   9          6d6h
kube-system            kube-proxy-c875m                             1/1     Running   8          6d7h
kube-system            kube-proxy-stg6w                             1/1     Running   10         6d6h
kube-system            kube-scheduler-k8s-master                    1/1     Running   9          6d7h
kubernetes-dashboard   dashboard-metrics-scraper-7b8b58dc8b-nr5fz   1/1     Running   7          6d1h
kubernetes-dashboard   kubernetes-dashboard-755dcb9575-9kg7p        1/1     Running   9          6d1h
[root@k8s-master ~]# kubectl get service --all-namespaces  # Or kubectl get service -A
NAMESPACE              NAME                        TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)                  AGE
default                kubernetes                  ClusterIP   10.96.0.1       <none>        443/TCP                  6d7h
kube-system            kube-dns                    ClusterIP   10.96.0.10      <none>        53/UDP,53/TCP,9153/TCP   6d7h
kubernetes-dashboard   dashboard-metrics-scraper   ClusterIP   10.104.12.221   <none>        8000/TCP                 6d1h
kubernetes-dashboard   kubernetes-dashboard        NodePort    10.110.157.29   <none>        443:30001/TCP            6d1h

3. flags: specifies an optional flag. For example, you can use the - s or -- server ID to specify the address and port of the Kubernetes API server- n specify the namespace; wait.

Note: the flags you specify from the command line will override the default value and any corresponding environment variables. Highest priority.

4. When performing operations on multiple resources, you can specify each resource by TYPE [TYPE] and NAME [NAME], or you can specify one or more files.

Specify resources by type and name:

# View multiple resources in a resource type
[root@k8s-master ~]# kubectl get pod -n kube-system coredns-6955765f44-c9zfh kube-proxy-28dwj
NAME                       READY   STATUS    RESTARTS   AGE
coredns-6955765f44-c9zfh   1/1     Running   8          6d7h
kube-proxy-28dwj           1/1     Running   9          6d6h
[root@k8s-master ~]#
# View multiple resource types
[root@k8s-master ~]# kubectl get svc,node
NAME                 TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   45h

NAME              STATUS   ROLES    AGE   VERSION
node/k8s-master   Ready    master   45h   v1.17.4
node/k8s-node01   Ready    <none>   45h   v1.17.4
node/k8s-node02   Ready    <none>   45h   v1.17.4

Specify a resource using one or more files: - F file1 - F File2 - f file < #>

1 # use YAML instead of JSON because YAML is easier to use, especially for configuration files.
2 kubectl get pod -f pod.yaml

command operation in kubectl syntax

The following table contains a short description and general syntax of common kubectl operations:

Some information can also be obtained on the command line through the kubectl -h command
Or see more details at:

1 https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
2 https://kubernetes.io/docs/reference/kubectl/overview/#operations

OperationSyntaxDescription
createkubectl create -f FILENAME [flags]Create one or more resources from a file or standard input ★★★
exposekubectl expose (-f FILENAMETYPE NAME
runkubectl run NAME –image=image [–env="key=value"] [–port=port] [–replicas=replicas] [–dry-run=bool] [–overrides=inline-json] [flags]Run the specified image on the cluster ★★★
explainkubectl explain [–recursive=false] [flags]Obtain documents of various resources. For example, pods, nodes, services, etc. ★★★★★
getkubectl get (-f FILENAMETYPE [NAME
editkubectl edit (-f FILENAMETYPE NAME
deletekubectl delete (-f FILENAMETYPE [NAME
rolloutkubectl rollout SUBCOMMAND [options]Manage resources. Valid resource types include deployments, daemonsets, and statefulsets
scalekubectl scale (-f FILENAMETYPE NAME
autoscalekubectl autoscale (-f FILENAMETYPE NAME
cluster-infokubectl cluster-info [flags]Display cluster information, and display endpoint information about hosts and services in the cluster. ★★★
topkubectl top node and kubectl top pod need heapster or metrics server supportDisplay resource (CPU / memory / storage) usage ★★★
cordonkubectl cordon NODE [options]Mark node as non schedulable
uncordonkubectl uncordon NODE [options]Mark node as schedulable
drainkubectl drain NODE [options]Exclude the specified node node to prepare for maintenance
taintkubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options]Update stains on one or more nodes ★★
describekubectl describe (-f FILENAMETYPE [NAME_PREFIX
logskubectl logs POD [-c CONTAINER] [–follow] [flags]Print the log of a container in the pod ★★★★
execkubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [– COMMAND [args...]]Execute commands on the container in the pod or enter the pod container ★★★★
proxykubectl proxy [–port=PORT] [–www=static-dir] [–www-prefix=prefix] [–api-prefix=prefix] [flags]Agent running Kubernetes API service
cpkubectl cp [options]Copy files and directories from the host to a container; Or copy files and directories from the container to the host ★★★
authkubectl auth [flags] [options]Check authorization
applykubectl apply -f FILENAME [flags]Apply the configuration to the resource through the content in the file name or stdin ★★★★
patchkubectl patch (-f FILENAMETYPE NAME
replacekubectl replace -f FILENAMEReplace resources with files or stdin
rolling-updatekubectl rolling-update OLD_CONTROLLER_NAME ([NEW_CONTROLLER_NAME] –image=NEW_CONTAINER_IMAGE-f NEW_CONTROLLER_SPEC) [flags]
labelkubectl label (-f FILENAMETYPE NAME
annotatekubectl annotate (-f FILENAMETYPE NAME
api-resourceskubectl api-resources [flags] [options]Print supported API resources ★★★
api-versionskubectl api-versions [flags]List available API versions ★★★
configkubectl config SUBCOMMAND [flags]Modify the kubeconfig file. For more information, see each subcommand
pluginkubectl plugin [flags] [options]Provides utilities to interact with plug-ins
versionkubectl version [–client] [flags]Displays the version of Kubernetes running on the client and server ★★★

TYPE resource in kubectl syntax

The following table contains a list of commonly used resource types and their abbreviations and aliases.

It can also be obtained through kubectl API resources on the command line.

Resource NameShort NamesNamespacedResource Kind
bindingsTRUEBinding
componentstatusescsFALSEComponentStatus
configmapscmTRUEConfigMap
endpointsepTRUEEndpoints
eventsevTRUEEvent
limitrangeslimitsTRUELimitRange
namespacesnsFALSENamespace
nodesnoFALSENode
persistentvolumeclaimspvcTRUEPersistentVolumeClaim
persistentvolumespvFALSEPersistentVolume
podspoTRUEPod
podtemplatesTRUEPodTemplate
replicationcontrollersrcTRUEReplicationController
resourcequotasquotaTRUEResourceQuota
secretsTRUESecret
serviceaccountssaTRUEServiceAccount
servicessvcTRUEService
mutatingwebhookconfigurationsFALSEMutatingWebhookConfiguration
validatingwebhookconfigurationsFALSEValidatingWebhookConfiguration
customresourcedefinitionscrd, crdsFALSECustomResourceDefinition
apiservicesFALSEAPIService
controllerrevisionsTRUEControllerRevision
daemonsetsdsTRUEDaemonSet
deploymentsdeployTRUEDeployment
replicasetsrsTRUEReplicaSet
statefulsetsstsTRUEStatefulSet
tokenreviewsFALSETokenReview
localsubjectaccessreviewsTRUELocalSubjectAccessReview
selfsubjectaccessreviewsFALSESelfSubjectAccessReview
selfsubjectrulesreviewsFALSESelfSubjectRulesReview
subjectaccessreviewsFALSESubjectAccessReview
horizontalpodautoscalershpaTRUEHorizontalPodAutoscaler
cronjobscjTRUECronJob
jobsTRUEJob
certificatesigningrequestscsrFALSECertificateSigningRequest
leasesTRUELease
endpointslicesTRUEEndpointSlice
eventsevTRUEEvent
ingressesingTRUEIngress
networkpoliciesnetpolTRUENetworkPolicy
runtimeclassesFALSERuntimeClass
poddisruptionbudgetspdbTRUEPodDisruptionBudget
podsecuritypoliciespspFALSEPodSecurityPolicy
clusterrolebindingsFALSEClusterRoleBinding
clusterrolesFALSEClusterRole
rolebindingsTRUERoleBinding
rolesTRUERole
priorityclassespcFALSEPriorityClass
csidriversFALSECSIDriver
csinodesFALSECSINode
storageclassesscFALSEStorageClass
volumeattachmentsFALSEVolumeAttachment

kubectl output options

Format output

The default output format for all kubectl commands is human readable plain text.

To output details to a terminal window in a specific format, you can add the - o or -- output ID to the supported kubectl command.

grammar

kubectl [command] [TYPE] [NAME] -o <output_format>

According to kubectl operation, the following output formats are supported:

Output formatDescription
-o custom-columns=Print the table using a comma separated list of custom columns
-o custom-columns-file=Print the table using a custom column template in the file
-o jsonOutput an API object in JSON format
-o jsonpath=Print the fields defined in the jsonpath expression
-o jsonpath-file=Print the fields defined by the jsonpath expression through the file
-o namePrint only the resource name and nothing else
-o wideOutput in plain text format with additional information. For pods, include the node name
-o yamlOutput an API object in YAML format

Example

wide example

[root@k8s-master ~]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   1          28h
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get pod -o wide
NAME         READY   STATUS    RESTARTS   AGE   IP           NODE         NOMINATED NODE   READINESS GATES
nginx-demo   1/1     Running   1          28h   10.244.3.9   k8s-node01   <none>           <none>

yaml example

[root@k8s-master ~]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   1          28h
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get pod -o yaml
apiVersion: v1
items:
- apiVersion: v1
  kind: Pod
  metadata:
    annotations:
..................

json example

[root@k8s-master ~]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   1          28h
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get pod -o json
{
    "apiVersion": "v1",
    "items": [
        {
            "apiVersion": "v1",
            "kind": "Pod",
            "metadata": {
                "annotations": {
..................

name example

[root@k8s-master ~]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   1          28h
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get pod -o name
pod/nginx-demo

Custom columns example

[root@k8s-master ~]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   1          29h
[root@k8s-master ~]#
[root@k8s-master ~]# kubectl get pods -o custom-columns=NAME:.metadata.name,UID:.metadata.uid,imageName:.spec.containers[0].image
NAME         UID                                    imageName
nginx-demo   08121fc6-969b-4b4e-9aa4-b990a5d02148   registry.cn-beijing.aliyuncs.com/google_registry/nginx:1.17

Description: custom columns = key: value; Where key means listed; Value indicates the information to be displayed. This value information can be obtained through - o json or - o yaml.

Custom columns file example

[root@k8s-master test]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   0          80s
[root@k8s-master test]#
# List and data source to display
[root@k8s-master test]# cat custom-col.conf
NAME          UID          imageName                containerPort
metadata.name metadata.uid spec.containers[0].image spec.containers[0].ports[0].containerPort
[root@k8s-master test]#
[root@k8s-master test]# kubectl get pod -o custom-columns-file=custom-col.conf
NAME         UID                                    imageName                                                     containerPort
nginx-demo   769dc3f4-2ffc-407c-a351-56b74ddaba4c   registry.cn-beijing.aliyuncs.com/google_registry/nginx:1.17   80

jsonpath example

[root@k8s-master test]# kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   0          13m
[root@k8s-master test]#
[root@k8s-master test]# kubectl get pods -o jsonpath='{.items[0].metadata.name},{.items[0].spec.containers[0].image}'
nginx-demo,registry.cn-beijing.aliyuncs.com/google_registry/nginx:1.17

Jsonpath file example

[root@k8s-master test]# kubectl get pod
NAME         READY   STATUS    RESTARTS   AGE
nginx-demo   1/1     Running   0          16m
[root@k8s-master test]#
# Data source to display
[root@k8s-master test]# cat custom-json.conf
{.items[0].metadata.name},{.items[0].spec.containers[0].image},{.items[0].spec.containers[0].ports[0].containerPort}
[root@k8s-master test]#
[root@k8s-master test]# kubectl get pod -o jsonpath-file=custom-json.conf
nginx-demo,registry.cn-beijing.aliyuncs.com/google_registry/nginx:1.17,80

Related reading

1,Overview of kubectl on the official website

2,Official website kubectl [flags]

3,Details of kubectl commands on the official website

complete!

Keywords: kubenetes

Added by busin3ss on Tue, 25 Jan 2022 03:02:00 +0200