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 -h
View the subcommand list -
kubectl options
View global options -
kubectl <command> --help
Check 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
kubectl config set-credentials myself --username=admin --password=secret
kubectl config set-cluster local-server --server=http://localhost:8080
kubectl config set-context default-context --cluster=local-server --user=myself --namespace=default
kubectl config use-context default-context
kubectl config view
Common command formats
- create:
kubectl run <name> --image=<image>
orkubectl create -f
- Query:
kubectl get <resource>
- renew
kubectl set
orkubectl 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:
kubectl get secret SECRET -o go-template='{{ . | base64decode }}'
Notice,kubectl run
Only 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:
source /usr/share/bash-completion/bash_completion
source <(kubectl completion bash)
MacOS zsh
source <(kubectl completion zsh)
Custom output columns
For example, query resource requests and restrictions for all Pods:
kubectl get pods --all-namespaces -o custom-columns=NS:.,NAME:.,"CPU(requests)":.[*].,"CPU(limits)":.[*].,"MEMORY(requests)":.[*].,"MEMORY(limits)":.[*].
Log viewing
kubectl logs
Used to display the content output by the program in the container to the standard output during the pod operation. anddockerThe logs command is similar.
# Return snapshot logs from pod nginx with only one container
kubectl logs nginx
# Return snapshot of previous terminated ruby container logs from pod web-1
kubectl logs -p -c ruby web-1
# Begin streaming the logs of the ruby container in pod web-1
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 attach
Used to connect to a running container. Similar to docker's attachment command.
# Get output from running pod 123456-7890, using the first container by default
kubectl attach 123456-7890
# Get output from ruby-container from pod 123456-7890
kubectl attach 123456-7890 -c ruby-container
# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890
# and sends stdout/stderr from 'bash' back to the client
kubectl attach 123456-7890 -c ruby-container -i -t
Options:
-c, --container='': Container name. If omitted, the first container in the pod will be chosen
-i, --stdin=false: Pass stdin to the container
-t, --tty=false: Stdin is a TTY
Execute commands inside the container
kubectl exec
Used to execute commands in a running container. Similar to docker's exec command.
# Get output from running 'date' from pod 123456-7890, using the first container by default
kubectl exec 123456-7890 date
# Get output from running 'date' in ruby-container from pod 123456-7890
kubectl exec 123456-7890 -c ruby-container date
# Switch to raw terminal mode, sends stdin to 'bash' in ruby-container from pod 123456-7890
# and sends stdout/stderr from 'bash' back to the client
kubectl exec 123456-7890 -c ruby-container -i -t -- bash -il
Options:
-c, --container='': Container name. If omitted, the first container in the pod will be chosen
-p, --pod='': Pod name
-i, --stdin=false: Pass stdin to the container
-t, --tty=false: Stdin is a TT
Port Forwarding
kubectl port-forward
Used to forward the local port to the specified Pod.
# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
kubectl port-forward mypod 5000 6000
# Listen on port 8888 locally, forwarding to 5000 in the pod
kubectl port-forward mypod 8888:5000
# Listen on a random port locally, forwarding to 5000 in the pod
kubectl port-forward mypod :5000
# Listen on a random port locally, forwarding to 5000 in the pod
kubectl port-forward mypod 0:5000
You can also forward the local port to a service, replication controller, or deployed port.
# Forward to deployment
kubectl port-forward deployment/redis-master 6379:6379
# Forward to replicaSet
kubectl port-forward rs/redis-master 6379:6379
# Forward to service
kubectl port-forward svc/redis-master 6379:6379
API Serveracting
kubectl proxy
The command provides an HTTP proxy for the Kubernetes API service.
$ kubectl proxy --port=8080
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
curl http://localhost:8080/api/v1/namespaces/default/pods
Note, if passed--address
A non-localhost address is specified, an unauthorized error will be reported when accessing port 8080. You can set--accept-hosts
To avoid this problem (This is not recommended for the production environment.):
kubectl proxy --address='0.0.0.0' --port=8080 --accept-hosts='^*$'
File copy
kubectl cp
Supports copying from containers or copying files into containers
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo <some-pod>:/tmp/bar -c <specific-container>
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace <some-namespace>
kubectl cp /tmp/foo <some-namespace>/<some-pod>:/tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
Options:
-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
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 cordon
Order.
If you recover, just need to runkubectl uncordon NODE
Change NODE to scheduleable state again.
Permission Check
kubectl auth
Two subcommands are provided to check the user's authentication status:
-
kubectl auth can-i
Check whether the user has permission to perform an operation, such as
# Check to see if I can create pods in any namespace
kubectl auth can-i create pods --all-namespaces
# Check to see if I can list deployments in my current namespace
kubectl auth can-i list
# Check to see if I can do everything in my current namespace ("*" means all)
kubectl auth can-i '*' '*'
# Check to see if I can get the job named "bar" in namespace "foo"
kubectl auth can-i list /bar -n foo
-
kubectl auth reconcile
Automatically fix problematic RBAC policies, such as
# Reconcile rbac resources from a file
kubectl auth reconcile -f
Simulate other users
kubectl supports simulating other users or groups to perform cluster management operations, such as
kubectl drain mynode --as=superman --as-group=system:masters
This is actually adding the following HTTP HEADER when requesting the Kubernetes API:
Impersonate-User: superman
Impersonate-Group: system:masters
View events
# View all events
kubectl get events --all-namespaces
# View events called nginx objects
kubectl get events --field-selector =nginx,=default
# Check out the service event named nginx
kubectl get events --field-selector =nginx,=default,=Service
# View Pod events
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/plugins
Or environment variableKUBECTL_PLUGINS_PATH
In the specified directory - The format of the plugin is
Subdirectories/executable files or scripts
And the subdirectory should includeConfiguration file
for example
$ tree
.
└── hello
└──
1 directory, 1 file
$ cat hello/
name: "hello"
shortDesc: "Hello kubectl plugin!"
command: "echo Hello plugins!"
$ kubectl plugin hello
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
# OS X
curl -LO /kubernetes-release/release/$(curl -s /kubernetes-release/release/)/bin/darwin/amd64/kubectl
# Linux
curl -LO /kubernetes-release/release/$(curl -s /kubernetes-release/release/)/bin/linux/amd64/kubectl
# Windows
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