web123456

Cry BEC listening

kubectl

kubectl isKubernetesofCommand Line Tools(CLI), an essential administrative tool for Kubernetes users and administrators.

kubectl provides a large number of subcommands to facilitate management of various functions in Kubernetes clusters. Here we will no longer list the formats of various subcommands, but will introduce the help of how to query commands.

  • kubectl -hView the subcommand list
  • kubectl optionsView global options
  • kubectl <command> --helpCheck the help of subcommands
  • kubectl [command] [PARAMS] -o=<format>Set output format (such as json, yaml, jsonpath, etc.)
  • kubectl explain [RESOURCE]View the definition of the resource

Configuration

The first step in using kubectl is to configure the Kubernetes cluster and authentication methods, including

  • cluster information: Kubernetes server address
  • User information: user name, password or key
  • Context: a combination of cluster, user information and Namespace

Example

 
  1. kubectl config set-credentials myself --username=admin --password=secret
  2. kubectl config set-cluster local-server --server=http://localhost:8080
  3. kubectl config set-context default-context --cluster=local-server --user=myself --namespace=default
  4. kubectl config use-context default-context
  5. kubectl config view

Common command formats

  • create:kubectl run <name> --image=<image>orkubectl create -f
  • Query:kubectl get <resource>
  • renewkubectl setorkubectl patch
  • delete:kubectl delete <resource> <name>orkubectl delete -f
  • Query the Pod IP:kubectl get pod <pod-name> -o jsonpath='{.}'
  • Execute commands in the container:kubectl exec -ti <pod-name> sh
  • Container log:kubectl logs [-f] <pod-name>
  • Export service:kubectl expose deploy <name> --port=80
  • Base64 decoding:
 
  1. kubectl get secret SECRET -o go-template='{{ . | base64decode }}'

Notice,kubectl runOnly several resources such as Pod, Replication Controller, Deployment, Job and CronJob are supported. The specific resource type is determined by parameters, and the default is Deployment:

The resource type created parameter
Pod --restart=Never
Replication Controller --generator=run/v1
Deployment --restart=Always
Job --restart=OnFailure
CronJob --schedule=<cron>

Automatic command line completion

LinuxSystem Bash:

 
  1. source /usr/share/bash-completion/bash_completion
  2. source <(kubectl completion bash)

MacOS zsh

 
  1. source <(kubectl completion zsh)

Custom output columns

For example, query resource requests and restrictions for all Pods:

 
  1. kubectl get pods --all-namespaces -o custom-columns=NS:.,NAME:.,"CPU(requests)":.[*].,"CPU(limits)":.[*].,"MEMORY(requests)":.[*].,"MEMORY(limits)":.[*].

Log viewing

kubectl logsUsed to display the content output by the program in the container to the standard output during the pod operation. anddockerThe logs command is similar.

 
  1. # Return snapshot logs from pod nginx with only one container
  2. kubectl logs nginx
  3. # Return snapshot of previous terminated ruby container logs from pod web-1
  4. kubectl logs -p -c ruby web-1
  5. # Begin streaming the logs of the ruby container in pod web-1
  6. kubectl logs -f -c ruby web-1

Note: kubectl can only view logs of a single container. If you want to view logs of multiple Pods at the same time, you can usestern. for example:stern --all-namespaces -l run=nginx

Connect to a running container

kubectl attachUsed to connect to a running container. Similar to docker's attachment command.

 
  1. # Get output from running pod 123456-7890, using the first container by default
  2. kubectl attach 123456-7890
  3. # Get output from ruby-container from pod 123456-7890
  4. kubectl attach 123456-7890 -c ruby-container
  5. # Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890
  6. # and sends stdout/stderr from 'bash' back to the client
  7. kubectl attach 123456-7890 -c ruby-container -i -t
  8. Options:
  9. -c, --container='': Container name. If omitted, the first container in the pod will be chosen
  10. -i, --stdin=false: Pass stdin to the container
  11. -t, --tty=false: Stdin is a TTY

Execute commands inside the container

kubectl execUsed to execute commands in a running container. Similar to docker's exec command.

 
  1. # Get output from running 'date' from pod 123456-7890, using the first container by default
  2. kubectl exec 123456-7890 date
  3. # Get output from running 'date' in ruby-container from pod 123456-7890
  4. kubectl exec 123456-7890 -c ruby-container date
  5. # Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890
  6. # and sends stdout/stderr from 'bash' back to the client
  7. kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il
  8. Options:
  9. -c, --container='': Container name. If omitted, the first container in the pod will be chosen
  10. -p, --pod='': Pod name
  11. -i, --stdin=false: Pass stdin to the container
  12. -t, --tty=false: Stdin is a TT

Port Forwarding

kubectl port-forwardUsed to forward the local port to the specified Pod.

 
  1. # Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
  2. kubectl port-forward mypod 5000 6000
  3. # Listen on port 8888 locally, forwarding to 5000 in the pod
  4. kubectl port-forward mypod 8888:5000
  5. # Listen on a random port locally, forwarding to 5000 in the pod
  6. kubectl port-forward mypod :5000
  7. # Listen on a random port locally, forwarding to 5000 in the pod
  8. kubectl port-forward mypod 0:5000

You can also forward the local port to a service, replication controller, or deployed port.

 
  1. # Forward to deployment
  2. kubectl port-forward deployment/redis-master 6379:6379
  3. # Forward to replicaSet
  4. kubectl port-forward rs/redis-master 6379:6379
  5. # Forward to service
  6. kubectl port-forward svc/redis-master 6379:6379

API Serveracting

kubectl proxyThe command provides an HTTP proxy for the Kubernetes API service.

 
  1. $ kubectl proxy --port=8080
  2. Starting to serve on 127.0.0.1:8080

Can be accessed through the proxy addresshttp://localhost:8080/api/To access Kubernetes API directly, such as querying Pod lists

 
  1. curl http://localhost:8080/api/v1/namespaces/default/pods

Note, if passed--addressA non-localhost address is specified, an unauthorized error will be reported when accessing port 8080. You can set--accept-hostsTo avoid this problem (This is not recommended for the production environment.):

 
  1. kubectl proxy --address='0.0.0.0' --port=8080 --accept-hosts='^*$'

File copy

kubectl cpSupports copying from containers or copying files into containers

 
  1. # Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
  2. kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
  3. # Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
  4. kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
  5. # Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
  6. kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
  7. # Copy /tmp/foo from a remote pod to /tmp/bar locally
  8. kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
  9. Options:
  10. -c, --container='': Container name. If omitted, the first container in the pod will be chosen

Note: File copy depends on the tar command, so the container needs to be able to execute the tar command.

kubectl drain

 
  1. kubectl drain NODE [Options]
  • It deletes the Pods created by ReplicationController, ReplicaSet, DaemonSet, StatefulSet or Job on the NODE
  • Don't delete mirror pods (because mirror pods cannot be deleted through the API)
  • If there are other types of pods (such as a pod that passes kubectl create directly without RC) and does not have the —force option, the command will fail directly
  • If the —force option is added to the command, these pods that are not created with ReplicationController, Job, or DaemonSet are forced to be deleted.

Sometimes you don't need an evict pod, you just need to mark itNodeNot invoked, can be usedkubectl cordonOrder.

If you recover, just need to runkubectl uncordon NODEChange NODE to scheduleable state again.

Permission Check

kubectl authTwo subcommands are provided to check the user's authentication status:

  • kubectl auth can-iCheck whether the user has permission to perform an operation, such as
 
  1. # Check to see if I can create pods in any namespace
  2. kubectl auth can-i create pods --all-namespaces
  3. # Check to see if I can list deployments in my current namespace
  4. kubectl auth can-i list
  5. # Check to see if I can do everything in my current namespace ("*" means all)
  6. kubectl auth can-i '*' '*'
  7. # Check to see if I can get the job named "bar" in namespace "foo"
  8. kubectl auth can-i list /bar -n foo
  • kubectl auth reconcileAutomatically fix problematic RBAC policies, such as
 
  1. # Reconcile rbac resources from a file
  2. kubectl auth reconcile -f

Simulate other users

kubectl supports simulating other users or groups to perform cluster management operations, such as

 
  1. kubectl drain mynode --as=superman --as-group=system:masters

This is actually adding the following HTTP HEADER when requesting the Kubernetes API:

 
  1. Impersonate-User: superman
  2. Impersonate-Group: system:masters

View events

 
  1. # View all events
  2. kubectl get events --all-namespaces
  3. # View events called nginx objects
  4. kubectl get events --field-selector =nginx,=default
  5. # Check out the service event named nginx
  6. kubectl get events --field-selector =nginx,=default,=Service
  7. # View Pod events
  8. kubectl get events --field-selector =nginx-85cb5867f-bs7pn,=Pod

kubectl plugin

The kubectl plug-in provides a mechanism to extend kubectl, such as adding new subcommands. The plug-in can be written in any language, just need to meet the following conditions

  • Plugins placed~/.kube/pluginsOr environment variableKUBECTL_PLUGINS_PATHIn the specified directory
  • The format of the plugin isSubdirectories/executable files or scriptsAnd the subdirectory should includeConfiguration file

for example

 
  1. $ tree
  2. .
  3. └── hello
  4. └──
  5. 1 directory, 1 file
  6. $ cat hello/
  7. name: "hello"
  8. shortDesc: "Hello kubectl plugin!"
  9. command: "echo Hello plugins!"
  10. $ kubectl plugin hello
  11. Hello plugins!

You can also usekrewTo manage kubectl plug-ins.

Original URI

kubectl can also be used to directly access the original URI, such as to accessMetrics APICan

  • kubectl get --raw /apis/metrics./v1beta1/nodes
  • kubectl get --raw /apis/metrics./v1beta1/pods
  • kubectl get --raw /apis/metrics./v1beta1/nodes/<node-name>
  • kubectl get --raw /apis/metrics./v1beta1/namespace/<namespace-name>/pods/<pod-name>

appendix

How to install kubectl

 
  1. # OS X
  2. curl -LO /kubernetes-release/release/$(curl -s /kubernetes-release/release/)/bin/darwin/amd64/kubectl
  3. # Linux
  4. curl -LO /kubernetes-release/release/$(curl -s /kubernetes-release/release/)/bin/linux/amd64/kubectl
  5. # Windows
  6. curl -LO /kubernetes-release/release/$(curl -s /kubernetes-release/release/)/bin/windows/amd64/

The current content copyright belongs tofeiskyerOr owned by its affiliates. If you need to pay attention to and fund content or content-related open source projects, please visitfeiskyer .

Previous article:hyperkube

Next article:Resource Objects