Kubectl overview

Kubernetes-handbook/Kubectl command overview, you can have a whole concept of command family.

Environment to prepare

To allow the pod to be deployed on the master node, run the following command:

kubectl taint nodes –all node-role.kubernetes.io/master-

After kubectl installation, the default is not such as automatic completion and other functions, frequent use is not convenient. There are already various Kubectl widgets to improve efficiency, as well as special Shells for Kubectl. I feel better to use the following:

  • Automatic completion

The kubectl command does not have autocompletion in bash by default, so you need to install bash_completion and add the autocompletion script. CentOS is used as an example. For other oss, see Install and Set Up kubectl

# bash installed - completion
yum install -y epel-release.noarch
yum install -y bash_completion
# Add completion script
kubectl completion bash >/etc/bash_completion.d/kubectlCopy the code

Kubectl subcommands, including resource names, are now tab-complete:

  • Quickly switch clusters and namespaces

The production environment is usually multi-cluster, or at least multi-NS environment. It is inevitable to switch between different clusters and NS. It is not very convenient to change the environment variable and follow the command -n namespace to change the NS. And with Kubectx and Kubens two small tools can achieve fast switching. These two are in the same project: Ahmetb/Kubectx

# installation
sudo git clone https://github.com/ahmetb/kubectx /opt/kubectx
sudo ln -s /opt/kubectx/kubectx /usr/local/bin/kubectx
sudo ln -s /opt/kubectx/kubens /usr/local/bin/kubens

# use kubectx
# kubectx: Lists all contexts
# kubectx 
       
         : Switch to a context
       
$ kubectx minikube
Switched to context "minikube".
# kubectx - : Switches back to the previous context
$ kubectx -
Switched to context "oregon".
# kubectx 
       
        =
        
          : Rename a cluster context
        
       
$ kubectx dublin=gke_ahmetb_europe-west1-b_dublin
Context "dublin" set.
Aliased "gke_ahmetb_europe-west1-b_dublin" as "dublin".
# kubectx 
       
        =. : Rename the current context
       
# kubectx -d 
       
         : Delete context
       

# use kubens
# kubens: List all NS
# kubens < ns-name > : switch the current NS
$ kubens kube-system
Context "test" set.
Active namespace is "kube-system".
# kubens - : Switch back to the previous NS
$ kubens -
Context "test" set.
Active namespace is "default".Copy the code

The concept of configuration and context for multi-cluster switching can be found in the official documentation in Chinese.

  • kubectl shell

Kubectl already has a mature dedicated shell, which is optimized for auto-completion, fuzzy matching and other functions:

But in the actual use of the process, occasionally there will be all kinds of small problems. Recommend two more popular, if you need to try:

kube-shell

kube-prompt

Description of common commands

Kubectl subcommands are categorized into the following subcommands:

grammar

$ kubectl [command] [TYPE] [NAME] [flags]Copy the code

Command: indicates a subcommand

TYPE: indicates the resource TYPE

NAME: indicates the resource NAME

Flags: command parameters

Command assistance

Kubectl command help is very detailed,

kubectl -h

All subcommands are listed, followed by -h for any subcommand, which outputs detailed help and use cases. You can view the help whenever you encounter problems.

Resource objects

Kubectl most of the molecular command can be specified after the operation of the resource object, can be used

kubectl api-resources

Command reference

Global parameters

kubectl options

The command can list the command parameters that can be used globally. The important ones are:

--cluster=' ': Specifies the cluster of command operation objects --context=' ': Specifies the context of the command operation object -n, --namespace=' ': Specifies the Namespace of the command operation objectCopy the code

Resource field

kubectl explain

The command outputs the property fields and definitions of resources, which is very useful in defining resource configuration files.

# Usage:
  kubectl explain RESOURCE [options]
# Examples: 
$ kubectl  explain deployment.spec.selector
KIND:     Deployment
VERSION:  extensions/v1beta1

RESOURCE: selector <Object>

DESCRIPTION:
     Label selector for pods. Existing ReplicaSets whose pods are selected by
     this will be the ones affected by this deployment.

     A label selector is a label query over a set of resources. The result of
     matchLabels and matchExpressions are ANDed. An empty label selector matches
     all objects. A null label selector matches no objects.

FIELDS:
   matchExpressions     <[]Object>
     matchExpressions is a list of label selector requirements. The requirements
     are ANDed.

   matchLabels  <map[string]string>
     matchLabels is a map of {key,value} pairs. A single {key,value} in the
     matchLabels map is equivalent to an element of matchExpressions, whose key
     field is "key", the operator is "In", and the values array contains only
     "value". The requirements are ANDed.Copy the code

Declarative resource object management

The declarative management of cluster resources is one of the most important features of Kubernetes, and the kubectl apply command is the best command to embody this feature. The main parameters of the apply command are:

# Usage:
  kubectl apply (-f FILENAME | -k DIRECTORY) [options]Copy the code

The -f argument is followed by the resource configuration file in yaml or JSON format, and the -k argument is followed by the location of the kustomization.yaml configuration file.

The reason why apply is declarative is that all changes to the cluster can be done using the Apply command, depending on the following configuration file:

  • If the resource search cluster in the configuration file does not exist, create the resource.
  • If the resource in the configuration file already exists in the cluster, the resource field is updated based on the configuration

Here’s an example:

Create a goWeb application with 4 pods:
[root@master-1 ~]# grep replicas deployment-goweb.yaml 
  replicas: 4
Create a resource using apply
[root@master-1 ~]# kubectl apply -f deployment-goweb.yaml 
deployment.apps/goweb created
[root@master-1 ~]# kubectl get po
NAME                     READY   STATUS    RESTARTS   AGE
goweb-6b5d559869-4x5mb   1/1     Running   0          14s
goweb-6b5d559869-77lbz   1/1     Running   0          14s
goweb-6b5d559869-9ztkh   1/1     Running   0          14s
goweb-6b5d559869-ccjtp   1/1     Running   0          14s

# change the number of pods to 2:
[root@master-1 ~]# sed -ri 's/4$/2/g' deployment-goweb.yaml
[root@master-1 ~]# grep replicas deployment-goweb.yaml       
  replicas: 2

Update resources using apply
[root@master-1 ~]# kubectl apply -f deployment-goweb.yaml
deployment.apps/goweb configured
[root@master-1 ~]# kubectl get po
NAME                     READY   STATUS    RESTARTS   AGE
goweb-6b5d559869-4x5mb   1/1     Running   0          8m21s
goweb-6b5d559869-77lbz   1/1     Running   0          8m21s

# Pod count has been updated to 2Copy the code

As you can see, the same thing

kubectl apply -f deployment-goweb.yaml

Command can be used to create or update resources.

Simply put, the apply command does one thing: change the actual state of the cluster to the desired state declared by the user, without the user having to worry about how to add, delete, or modify the desired state, namely Kubernetes’ declarative resource management.

Imperative resource object management

Kubernetes recommends using the apply command instead of using the command to delete resources.

Create a resource

kubectl create deployment my-dep --image=busybox        Create a deplpyme
kubectl expose rc nginx --port=80 --target-port=8000    # create an SVC to expose nginx rcCopy the code

Update the resource

kubectl scale --replicas=3 -f foo.yaml                     # Extend the objects described in foo.yaml to three
kubectl annotate pods foo description='my frontend'        # add description='my frontend' remarks
kubectl label --overwrite pods foo status=unhealthy        This is what I want to do. # Add the status=unhealthy tagCopy the code

Delete the resource

kubectl delete -f xxx.yaml                      Delete a resource object corresponding to a configuration file
kubectl delete pod,service baz foo              # delete pod and service named baz or foo
kubectl delete pods,services -l name=myLabel    The # -l argument deletes the resource object that contains the specified label
kubectl delete pod foo --grace-period=0 --force Delete a POD forcibly. This is useful when pod terminates for any reasonCopy the code

Viewing Resource Status

get

The most commonly used view command displays detailed information about one or more resources

# Usage:
  kubectl get
[(-o|--output=)](TYPE[.VERSION][.GROUP] [NAME | -l label] | TYPE[.VERSION][.GROUP]/NAME ...) [flags] 
[options]
# Examples: 
kubectl get services                          List all service resources in the current NS
kubectl get pods --all-namespaces             # list all pods in all NS in the cluster
kubectl get pods -o wide                      -o wide is also used to display more resource information, such as the IP of the pod, etc
kubectl get deployment my-dep                 You can directly specify the resource name to view
kubectl get deployment my-dep --watch         The watch parameter monitors the state of the resource and prints it when the state changes. Useful for tracking service deployment
kubectl get pod my-pod -o yaml                # check the yamL resource configuration, including the actual status, can be excluded with --export
kubectl get pod my-pod -l app=nginx           # View all pods with the tag app: nginxCopy the code

Kubectl uses JSONPATH to filter fields. JSON Path syntax can be found here

kubectl get pods --selector=app=cassandra rc -o jsonpath='{.items[*].metadata.labels.version}' Get the version tag in all pods with app= CassandraCopy the code

describe

The describe command is also used to view information about a resource, but instead of getting only outputs information about the resource itself, describe aggregates information about related resources and outputs it. For example, when describing node information, resource utilization of the PODS under the node is also output. So the describe command is very useful for troubleshooting and debugging.

# Usage:
kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options]
# Examples: 
kubectl describe nodes my-node    My-node = my-node
kubectl describe pods my-pod      View details about pod my-podCopy the code

Container management

Although logically the minimum unit of management for Kubernetes is a Pod, it is practically unavoidable to interact directly with containers, especially for multi-container PODS, and problems with any container will result in Pod unusable.

The log view

# Usage:
  kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options]
# Examples: 
kubectl logs my-pod                              
Output a single pod my-pod log to standard output
kubectl logs nginx-78f5d695bd-czm8z -c nginx     
Output a log for an Nginx container in a multi-container POD
kubectl logs -l app=nginx                        
Output all pod logs containing the app-nginx tag
kubectl logs -f my-pod                           
# add -f parameter trace log, similar to tail -f
kubectl logs my-pod  -p                          
Output the last container instance log for this pod to exit. Useful when the POD container exits unexpectedly
kubectl logs my-pod  --since-time=2018-11-01T15:00:00Z
# specify timestamp to output log
kubectl logs my-pod  --since=1h 
The unit is s/m/hCopy the code

Execute the command

The command functions and parameters are basically the same as those of Docker exec

# Usage:
kubectl execPOD [-c CONTAINER] -- COMMAND [args...]  [options]# Examples:
kubectl exec my-pod ls                         # execute ls on my-pod
kubectl exec -t -i nginx-78f5d695bd-czm8z bash Enter the pod shell and open the dummy terminal and standard inputCopy the code

The file transfer

The *kubectl cp command is used when you need to exchange files with the container during troubleshooting and testing, such as transferring the container memory dump to the host or temporarily copying a new configuration file from the host for debugging. Note that the cp command requires the tar program to be installed in the container

# Usage:
kubectl cp <file-spec-src> <file-spec-dest> [options]
# Examples:  
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir                 Copy the host local folder to pod
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar        Copy the POD file of the namespace to the local directory of the host
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container> For multi-container pods, use -c to specify the container nameCopy the code

Cluster management

In addition to dealing with specific resources, you also need to view cluster information and manage nodes during cluster maintenance. The following commands are commonly used for cluster management:

Viewing Cluster Information

kubectl cluster-info      Master and cluster service address
 kubectl cluster-info dump View the cluster details log
 kubectl version           Check Kubernetes cluster and client versionsCopy the code

Node management

In the event of a cluster node problem, you might want to either remove a node from the scheduled POD, or expel the node’s current POD altogether

kubectl cordon my-node       
# mark my-node as unschedulable to prevent pod from being scheduled. Note that the existing POD will continue to run and will not be expelled.
kubectl uncordon my-node 
# In contrast to Cordon, mark my-node to allow scheduling.
kubectl drain  my-node
The # drain command is used to smoothly switch the pod from my-node to another node and marks the pod as unschedulable, which includes the Cordon command.
If you want to maintain a node, add the following parameters:
kubectl drain my-node  --ignore-daemonsets  --force  --delete-local-data  
# --ignore-daemonsets Ignore the pod deployed on daemonset
# --force directly removes pods that are not managed by workload objects (Deployment, Job, etc.)
# --delete-local-data directly delete pod mounted with local directory (empty-dir)
Copy the code


K8s Pod restart method

Yaml files are up to date

kubectl replace –force -f xxxx.yaml 

There are no YAML files, but Deployment objects are used.

 kubectl scale deployment esb-admin –replicas=0 -n {namespace} 

kubectl scale deployment esb-admin –replicas=1 -n {namespace} 

This is because the Deployment object is not a directly managed Pod object, but a ReplicaSet object, which consists of a definition of the number of replicas and a Pod template. Scale the number of ReplicaSet replicas to 0 and then to 1, and the Pod restarts.