kubectl 是 Kubernetes 的命令行工具(CLI),是 Kubernetes 用户和管理员必备的管理工具。kubectl安装在k8s的master节点,kubectl在$HOME/.kube目录中查找一个名为config的文件, 你可以通过设置Kubeconfig环境变量或设置--kubeconfig来指定其他的kubeconfig文件。kubectl通过与apiserver交互可以实现对k8s集群中各种资源的增删改查。
kubectl 提供了大量的子命令,方便管理 Kubernetes 集群中的各种功能。这里不再罗列各种子命令的格式,而是介绍下如何查询命令的帮助:
使用 kubectl 的第一步是配置 Kubernetes 集群以及认证方式,包括:
示例
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
默认情况下,kubectl 命令首先确定它是否在 Pod 中运行,从而被视为在集群中运行。 它首先检查 KUBERNETES_SERVICE_HOST 和 KUBERNETES_SERVICE_PORT 环境变量以及 /var/run/secrets/kubernetes.io/serviceaccount/token 中是否存在服务帐户令牌文件。 如果三个条件都被满足,则假定在集群内进行身份验证。
为保持向后兼容性,如果在集群内身份验证期间设置了 POD_NAMESPACE 环境变量,它将覆盖服务帐户令牌中的默认命名空间。 任何依赖默认命名空间的清单或工具都会受到影响。
POD_NAMESPACE 环境变量
如果设置了 POD_NAMESPACE 环境变量,对命名空间资源的 CLI 操作对象将使用该变量值作为默认值。 例如,如果该变量设置为 seattle,kubectl get pods 将返回 seattle 命名空间中的 Pod。 这是因为 Pod 是一个命名空间资源,且命令中没有提供命名空间。
直接使用 --namespace 会覆盖此行为。
假设:
然后 kubectl 假定它正在你的集群中运行。 kubectl 工具查找该 ServiceAccount 的命名空间 (该命名空间与 Pod 的命名空间相同)并针对该命名空间进行操作。 这与集群外运行的情况不同; 当 kubectl 在集群外运行并且你没有指定命名空间时, kubectl 命令会针对 default 命名空间进行操作。
kubectl 的安装方法:
# OS X
curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/darwin/amd64/kubectl
# Linux
curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl
# Windows
curl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/windows/amd64/kubectl.exe
kubectl语法格式如下,可在k8s集群的master节点执行:
kubectl [command] [TYPE] [NAME] [flags]
上述语法解释说明:
kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1
注意事项说明:
从命令行指定的参数会覆盖默认值和任何相应的环境变量。
1.在对多个资源执行操作时,可以按类型、名称、一个或者多个文件指定每个资源:
1)按类型和名称指定资源:
a.要对所有类型相同的资源进行分组,请执行以下操作:
TYPE1 name1 name2 name
例子:
kubectl get pod example-pod1 example-pod2
b.分别指定多个资源类型:
TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE/name
例子:
kubectl get pod/example-pod1 deployment/example-rc1
2)用一个或多个文件指定资源:-f file1 -f file2 -f file
使用YAML而不是JSON,因为YAML更容易使用,特别是用于配置文件时。例子:
kubectl get pod -f ./pod.yaml
2.kubectl –-help
可查看kubectl的帮助命令。
kubectl run --image= 或者
kubectl create -f manifest.yaml
kubectl get
kubectl set 或者
kubectl patch
kubectl delete 或者
kubectl delete -f manifest.yaml
kubectl get pod -o jsonpath='{.status.podIP}'
kubectl exec -ti sh
kubectl logs [-f]
kubectl expose deploy --port=80
kubectl get secret SECRET -o go-template='{{ .data.KEY | base64decode }}'
注意,kubectl run 仅支持 Pod、Replication Controller、Deployment、Job 和 CronJob 等几种资源。具体的资源类型是由参数决定的,默认为 Deployment:
创建的资源类型 |
参数 |
Pod |
--restart=Never |
Replication Controller |
--generator=run/v1 |
Deployment |
--restart=Always |
Job |
--restart=OnFailure |
CronJob |
--schedule= |
Linux 系统 Bash:
source /usr/share/bash-completion/bash_completion source <(kubectl completion bash)
MacOS zsh
source <(kubectl completion zsh)
比如,查询所有 Pod 的资源请求和限制:
kubectl get pods --all-namespaces -o custom-columns=NS:.metadata.namespace,NAME:.metadata.name,"CPU(requests)":.spec.containers[*].resources.requests.cpu,"CPU(limits)":.spec.containers[*].resources.limits.cpu,"MEMORY(requests)":.spec.containers[*].resources.requests.memory,"MEMORY(limits)":.spec.containers[*].resources.limits.memory
kubectl logs 用于显示 pod 运行中,容器内程序输出到标准输出的内容。跟 docker 的 logs 命令类似。
# 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
注:kubectl 只可以查看单个容器的日志,如果想要同时查看多个 Pod 的日志,可以使用 stern。比如: stern --all-namespaces -l run=nginx。
attach 用于连接到一个正在运行的容器。跟 docker 的 attach 命令类似。
# 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
kubectl exec 用于在一个正在运行的容器执行命令。跟 docker 的 exec 命令类似。
# 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
kubectl port-forward 用于将本地端口转发到指定的 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
也可以将本地端口转发到服务、复制控制器或者部署的端口。
# 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
kubectl proxy 命令提供了一个 Kubernetes API 服务的 HTTP 代理。
$ kubectl proxy --port=8080 Starting to serve on 127.0.0.1:8080
可以通过代理地址 http://localhost:8080/api/ 来直接访问 Kubernetes API,比如查询 Pod 列表:
curl http://localhost:8080/api/v1/namespaces/default/pods
注意,如果通过 --address 指定了非 localhost 的地址,则访问 8080 端口时会报未授权的错误,可以设置 --accept-hosts 来避免这个问题( 不推荐生产环境这么设置 ):
kubectl proxy --address='0.0.0.0' --port=8080 --accept-hosts='^*$'
kubectl cp 支持从容器中拷贝,或者拷贝文件到容器中:
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
kubectl cp /tmp/foo_dir :/tmp/bar_dir
# Copy /tmp/foo local file to /tmp/bar in a remote pod in a specific container
kubectl cp /tmp/foo :/tmp/bar -c
# Copy /tmp/foo local file to /tmp/bar in a remote pod in namespace
kubectl cp /tmp/foo /:/tmp/bar
# Copy /tmp/foo from a remote pod to /tmp/bar locally
kubectl cp /:/tmp/foo /tmp/bar
Options:
-c, --container='': Container name. If omitted, the first container in the pod will be chosen
注意:文件拷贝依赖于 tar 命令,所以容器中需要能够执行 tar 命令。
kubectl drain NODE [Options]
有的时候不需要 evict pod,只需要标记 Node 不可调用,可以用 kubectl cordon 命令。
恢复的话只需要运行 kubectl uncordon NODE 将 NODE 重新改成可调度状态。
kubectl auth 提供了两个子命令用于检查用户的鉴权情况:
# 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 deployments.extensions
# 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 jobs.batch/bar -n foo
# Reconcile rbac resources from a file
kubectl auth reconcile -f my-rbac-rules.yaml
kubectl 支持模拟其他用户或者组来进行集群管理操作,比如:
kubectl drain mynode --as=superman --as-group=system:masters
这实际上就是在请求 Kubernetes API 时添加了如下的 HTTP HEADER:
Impersonate-User: superman
Impersonate-Group: system:masters
# 查看所有事件
kubectl get events --all-namespaces
# 查看名为nginx对象的事件
kubectl get events --field-selector involvedObject.name=nginx,involvedObject.namespace=default
# 查看名为nginx的服务事件
kubectl get events --field-selector involvedObject.name=nginx,involvedObject.namespace=default,involvedObject.kind=Service
# 查看Pod的事件
kubectl get events --field-selector involvedObject.name=nginx-85cb5867f-bs7pn,involvedObject.kind=Pod
kubectl 也可以用来直接访问原始 URI,比如要访问 Metrics API 可以:
kubectl 插件提供了一种扩展 kubectl 的机制,比如添加新的子命令。插件可以以任何语言编写,只需要满足以下条件即可:
比如
$ tree
.
└── hello
└── plugin.yaml
1 directory, 1 file
$ cat hello/plugin.yaml
name: "hello"
shortDesc: "Hello kubectl plugin!"
command: "echo Hello plugins!"
$ kubectl plugin hello
Hello plugins!
你也可以使用 krew 来管理 kubectl 插件。
kubectl · Kubernetes指南
kubectl基础命令详解(一)_OSoooo的博客-CSDN博客_kubectl
kubectl简介 - 快乐嘉年华 - 博客园
kubectl工具详解_pipipipe的博客-CSDN博客_kubectl工具
命令行工具 (kubectl) | Kubernetes
kubectl - 知乎
kubectl详解 - 明王不动心 - 博客园