Kubectl是一个用于操作kubernetes集群的命令行接口,通过利用kubectl的各种命令可以实现各种功能,是在使用kubernetes中非常常用的工具。
接下来我们会通过一些简单的实例来展现其中一些高频命令的使用方法,更为重要的是这些命令使用的场景以及能够解决什么样的问题。
环境构成
- 集群:
类型 | 主机名 | IP |
---|---|---|
Master | master | 192.168.30.128 |
Master | master2 | 192.168.30.150 |
Node | node1 | 192.168.30.129 |
Node | node2 | 192.168.30.130 |
# kubectl get nodes
NAME STATUS ROLES AGE VERSION
192.168.30.129 Ready node 11d v1.11.6
192.168.30.130 Ready node 11d v1.11.6
192.168.30.128 Ready,SchedulingDisabled master 11d v1.11.6
192.168.30.150 Ready,SchedulingDisabled master 11d v1.11.6
- 版本:
# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.6", GitCommit:"b1d75deca493a24a2f87eb1efde1a569e52fc8d9", GitTreeState:"clean", BuildDate:"2018-12-16T04:39:52Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.6", GitCommit:"b1d75deca493a24a2f87eb1efde1a569e52fc8d9", GitTreeState:"clean", BuildDate:"2018-12-16T04:30:10Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}
高级命令
用kubectl help可以查看kubectl相关的命令。
Basic Commands (Beginner):
create Create a resource from a file or from stdin.
expose 使用 replication controller, service, deployment 或者 pod 并暴露它作为一个 新的
Kubernetes Service
run 在集群中运行一个指定的镜像
set 为 objects 设置一个指定的特征
Basic Commands (Intermediate):
explain 查看资源的文档
get 显示一个或更多 resources
edit 在服务器上编辑一个资源
delete Delete resources by filenames, stdin, resources and names, or by resources and label selector
Deploy Commands:
rollout Manage the rollout of a resource
scale 为 Deployment, ReplicaSet, Replication Controller 或者 Job 设置一个新的副本数量
autoscale 自动调整一个 Deployment, ReplicaSet, 或者 ReplicationController 的副本数量
Cluster Management Commands:
certificate 修改 certificate 资源.
cluster-info 显示集群信息
top Display Resource (CPU/Memory/Storage) usage.
cordon 标记 node 为 unschedulable
uncordon 标记 node 为 schedulable
drain Drain node in preparation for maintenance
taint 更新一个或者多个 node 上的 taints
Troubleshooting and Debugging Commands:
describe 显示一个指定 resource 或者 group 的 resources 详情
logs 输出容器在 pod 中的日志
attach Attach 到一个运行中的 container
exec 在一个 container 中执行一个命令
port-forward Forward one or more local ports to a pod
proxy 运行一个 proxy 到 Kubernetes API server
cp 复制 files 和 directories 到 containers 和从容器中复制 files 和 directories.
auth Inspect authorization
Advanced Commands:
apply 通过文件名或标准输入流(stdin)对资源进行配置
patch 使用 strategic merge patch 更新一个资源的 field(s)
replace 通过 filename 或者 stdin替换一个资源
wait Experimental: Wait for one condition on one or many resources
convert 将配置文件转换为不同的API Version
Settings Commands:
label 更新在这个资源上的 labels
annotate 更新一个资源的注解
completion Output shell completion code for the specified shell (bash or zsh)
Other Commands:
alpha Commands for features in alpha
api-resources Print the supported API resources on the server
api-versions Print the supported API versions on the server, in the form of "group/version"
config 修改 kubeconfig 文件
plugin Runs a command-line plugin
version 输出 client 和 server 的版本信息
下面将会简单介绍一下高级命令:
命令 | 说明 |
---|---|
apply | 通过文件名或标准输入(stdin)对资源进行配置 |
patch | 更新资源的字段 |
replace | 用文件名或标准输入替换资源 |
wait | 在一个或多个资源上等待一个条件 |
convert | 将配置文件转换为不同的API Version |
apply
kubectl apply通过文件名或标准输入(stdin)对资源进行配置。支持JSON和YAML格式的描述文件。
以service “nginx”为例,先准备两个yaml文件。
# vim nginx-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: nginx:1.14
name: nginx
ports:
- containerPort: 80
# vim nginx-svc.yaml
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort
ports:
- port: 80
nodePort : 30001
selector:
app: nginx
# kubectl create -f nginx-deploy.yaml
deployment.apps/nginx created
# kubectl create -f nginx-svc.yaml
service/nginx created
# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.68.0.1 <none> 443/TCP 11d
nginx NodePort 10.68.63.117 <none> 80:30001/TCP 1m
修改nginx-svc.yaml文件,将nodePort改为30002。
# grep nodePort nginx-svc.yaml
nodePort : 30002
# kubectl apply -f nginx-svc.yaml
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
service/nginx configured
# kubectl get svc
NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE
kubernetes ClusterIP 10.68.0.1 <none> 443/TCP 11d
nginx NodePort 10.68.63.117 <none> 80:30002/TCP 5m
可以看到,nodePort已经变成了30002。通过apply,用户可以将resource的configuration使用source control的方式维护在版本库中。每次有更新时,将配置文件push到server,然后使用kubectl apply将更新应用到resource。kubernetes会在引用更新前将当前配置文件中的配置同已经应用的配置做比较,并只更新更改的部分,而不会主动更改任何用户未指定的部分。
patch
kubectl patch用于更新资源的字段。当部分修改一些设定的时候patch非常有用。支持JSON和YAML格式。
这次以更改nginx版本为例。
# kubectl exec -it nginx-666486ddc5-q62w6 bash
root@nginx-666486ddc5-q62w6:/# nginx -v
nginx version: nginx/1.14.2
root@nginx-666486ddc5-q62w6:/# exit
# kubectl patch pod nginx-666486ddc5-q62w6 -p '{"spec":{"containers":[{"name":"nginx","image":"nginx:1.12"}]}}'
pod/nginx-666486ddc5-q62w6 patched
# kubectl exec -it nginx-666486ddc5-q62w6 bash
root@nginx-666486ddc5-q62w6:/# nginx -v
nginx version: nginx/1.12.2
可以看到,nginx的版本变成了1.12.2,而之前版本是1.14.2。不过需要注意的是,patch修改的是pod本身,而不是yaml文件,而且不会重新生成pod。
replace
kubectl replace用文件名或标准输入替换资源。支持JSON和YAML格式。作用类似于apply,不同的是,apply不会删除原有resource,然后创建新的。apply直接在原有resource的基础上进行更新。同时kubectl apply还会resource中添加一条注释,标记当前的apply。类似于git操作。
还是以更改nginx版本为例。
# sed -i 's/nginx:1.14/nginx:1.15/g' nginx-deploy.yaml
# cat nginx-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
labels:
app: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- image: nginx:1.15
name: nginx
ports:
- containerPort: 80
# kubectl replace -f nginx-deploy.yaml
deployment.apps/nginx replaced
# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-666486ddc5-q62w6 0/1 Terminating 1 31m
nginx-c9bd9bc4-8hnbx 1/1 Running 0 10s
# kubectl get pod
NAME READY STATUS RESTARTS AGE
nginx-c9bd9bc4-8hnbx 1/1 Running 0 1m
# kubectl exec -it nginx-c9bd9bc4-8hnbx bash
root@nginx-c9bd9bc4-8hnbx:/# nginx -v
nginx version: nginx/1.15.9
可以看到,nginx版本已经变成了1.15。此外,replace会重新生成pod并删除原pod。如果是更新label,原有标签的pod将会与更新label后的deploy断开联系,有新label的deploy将会创建指定副本数的新的pod,但是默认并不会删除原来的pod。
wait
kubectl wait在一个或多个资源上等待一个条件。该命令不常用。
有以下选项:
--all-namespaces=false: 如果存在,列出所有名称空间中请求的对象。名称空间在当前即使使用--namespace指定上下文,也会忽略上下文。
--allow-missing-template-keys=true: 如果为真,则忽略模板中缺少字段或映射键时的任何错误的模板。仅适用于golang和jsonpath输出格式。
-f, --filename=[]: 标识资源。
--for='': 等待的条件:[删除|条件=条件名称]。
-o, --output='': 输出格式之一:
json|yaml|name|template|go-template|go-template-file|templatefile|jsonpath-file|jsonpath。
-R, --recursive=true: 递归地处理-f,--filename中使用的目录。当您想要管理相关内容时,它在同一个目录中组织的清单非常有用。
-l, --selector='': 过滤选择器(标签查询),支持“=”、“==”和“!=”。(如 -l key1 = value1, key2 = value2)
--template='': 模板字符串或模板文件路径,当-o=go-template,-o=go-template-file时使用。
--timeout=30s: 放弃前等待的时间长度。0表示检查一次,不要等待,负的表示等一个星期。
convert
kubectl convert转换配置文件为不同的API版本。支持YAML和JSON格式。
该命令将配置文件名,目录或URL作为输入,并将其转换为指定的版本格式,如果目标版本未指定或不支持,则转换为最新版本。
# kubectl convert -f nginx-deploy.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
creationTimestamp: null
labels:
app: nginx
name: nginx
spec:
progressDeadlineSeconds: 600
replicas: 1
revisionHistoryLimit: 10
selector:
matchLabels:
app: nginx
strategy:
rollingUpdate:
maxSurge: 25%
maxUnavailable: 25%
type: RollingUpdate
template:
metadata:
creationTimestamp: null
labels:
app: nginx
spec:
containers:
- image: nginx:1.15
imagePullPolicy: IfNotPresent
name: nginx
ports:
- containerPort: 80
protocol: TCP
resources: {}
terminationMessagePath: /dev/termination-log
terminationMessagePolicy: File
dnsPolicy: ClusterFirst
restartPolicy: Always
schedulerName: default-scheduler
securityContext: {}
terminationGracePeriodSeconds: 30
status: {}
这样的话,我们可以将当前所有的配置文件转换为最新版本,然后再将其全部创建。
设置命令
下面将会简单介绍一下设置命令:
命令 | 说明 |
---|---|
label | 更新资源的标签 |
annotate | 更新资源的注解 |
completion | 输出指定shell的代码完成命令 (bash or zsh) |
label
kubectl label用来更新(增加、修改或删除)资源上的 label(标签)。
- label 必须以字母或数字开头,可以使用字母、数字、连字符、点和下划线,最长63个字符。
- 如果–overwrite 为 true,则可以覆盖已有的 label,否则尝试覆盖 label 将会报错。
- 如果指定了–resource-version,则更新将使用此资源版本,否则将使用现有的资源版本。
增加标签:
# kubectl label pod nginx-c9bd9bc4-8hnbx status=healthy
pod/nginx-c9bd9bc4-8hnbx labeled
# kubectl describe pod nginx-c9bd9bc4-8hnbx
Name: nginx-c9bd9bc4-8hnbx
Namespace: default
Node: 192.168.30.129/192.168.30.129
Start Time: Wed, 06 Mar 2019 11:16:02 +0800
Labels: app=nginx
pod-template-hash=75685670
status=healthy
删除标签:
# kubectl label pod nginx-c9bd9bc4-8hnbx status-
pod/nginx-c9bd9bc4-8hnbx labeled
# kubectl describe pod nginx-c9bd9bc4-8hnbx
Name: nginx-c9bd9bc4-8hnbx
Namespace: default
Node: 192.168.1.233/192.168.1.233
Start Time: Wed, 06 Mar 2019 11:16:02 +0800
Labels: app=nginx
pod-template-hash=75685670
在标签名后跟“-”即可删除对应标签名的标签。
annotate
kubectl annotate用来更新一个或多个资源的注释信息。
- Annotations由key/value组成。目的是存储辅助数据,特别是通过工具和系统扩展操作的数据,更多介绍在这里。
- 如果–overwrite为true,现有的annotations可以被覆盖,否则试图覆盖annotations将会报错。
- 如果设置了–resource-version,则更新将使用此resource version,否则将使用原有的resource version。
用法和label有点类似。增加注释:
# kubectl annotate pod nginx-c9bd9bc4-8hnbx description="running nginx"
pod/nginx-c9bd9bc4-8hnbx annotated
# kubectl describe pod nginx-c9bd9bc4-8hnbx
Name: nginx-c9bd9bc4-8hnbx
Namespace: default
Node: 192.168.1.233/192.168.1.233
Start Time: Wed, 06 Mar 2019 11:16:02 +0800
Labels: app=nginx
pod-template-hash=75685670
Annotations: description=running nginx
删除注释:
# kubectl annotate pod nginx-c9bd9bc4-8hnbx description-
pod/nginx-c9bd9bc4-8hnbx annotated
# kubectl describe pod nginx-c9bd9bc4-8hnbx
Name: nginx-c9bd9bc4-8hnbx
Namespace: default
Node: 192.168.1.233/192.168.1.233
Start Time: Wed, 06 Mar 2019 11:16:02 +0800
Labels: app=nginx
pod-template-hash=75685670
Annotations: <none>
在注释名后跟“-”即可删除对应注释名的注释。
completion
kubectl completion输出指定shell的代码完成命令 (bash or zsh)。该命令可用于自动补全。该命令不常用。
在linux上
# yum install -y bash-completion
# locate bash_completion
/usr/share/bash-completion/bash_completion
# source /usr/share/bash-completion/bash_completion
# source <(kubectl completion bash)
其它命令
下面将会简单介绍一下其它命令:
命令 | 说明 |
---|---|
alpha | 对应于alpha中特性的命令 |
api-resources | 打印受支持的API资源 |
api-versions | 打印支持的API版本 |
config | 用来修改kubeconfig文件 |
plugin | 用来运行命令行插件 |
version | 打印当前上下文的客户机和服务器版本信息 |
alpha
kubectl alpha是对应于alpha中特性的命令。该命令不常用。
用法:
kubectl alpha diff -f/--filename=
api-resources
kubectl api-resources打印受支持的API资源。
# kubectl api-resources
NAME SHORTNAMES APIGROUP NAMESPACED KIND
bindings true Binding
componentstatuses cs false ComponentStatus
configmaps cm true ConfigMap
endpoints ep true Endpoints
events ev true Event
limitranges limits true LimitRange
namespaces ns false Namespace
nodes no false Node
persistentvolumeclaims pvc true PersistentVolumeClaim
persistentvolumes pv false PersistentVolume
pods po true Pod
podtemplates true PodTemplate
replicationcontrollers rc true ReplicationController
resourcequotas quota true ResourceQuota
secrets true Secret
serviceaccounts sa true ServiceAccount
services svc true Service
api-versions
kubectl api-versions打印支持的API版本。
# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
batch/v1
batch/v1beta1
batch/v2alpha1
certificates.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1
config
kubectl config用来修改kubeconfig文件。
子命令:
current-context 显示当前上下文
delete-cluster 从kubeconfig中删除指定的集群
delete-context 从kubeconfig中删除指定的上下文
get-clusters 显示kubeconfig中定义的集群
get-context 描述一个或多个上下文
rename-context 从kubeconfig文件重命名上下文。
set 在kubeconfig文件中设置一个单独的值
set-cluster 在kubeconfig中设置一个集群条目
set-context 在kubeconfig中设置一个上下文条目
set-credentials 在kubeconfig中设置一个用户条目
unset 取消设置kubeconfig文件中的单个值
use-context 在kubeconfig文件中设置当前上下文
view 显示合并的kubeconfig设置或指定的kubeconfig文件
# kubectl config view
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: REDACTED
server: https://192.168.1.52:8443
name: kubernetes
contexts:
- context:
cluster: kubernetes
user: admin
name: kubernetes
current-context: kubernetes
kind: Config
preferences: {}
users:
- name: admin
user:
client-certificate-data: REDACTED
client-key-data: REDACTED
# kubectl config current-context
kubernetes
# kubectl config get-clusters
NAME
kubernetes
plugin
kubectl plugin用来运行命令行插件。插件可以是不属于主要命令行发行版的子命令,甚至可以由第三方提供。该命令不常用。
version
kubectl version打印当前上下文的客户机和服务器版本信息。
# kubectl version
Client Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.6", GitCommit:"b1d75deca493a24a2f87eb1efde1a569e52fc8d9", GitTreeState:"clean", BuildDate:"2018-12-16T04:39:52Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"11", GitVersion:"v1.11.6", GitCommit:"b1d75deca493a24a2f87eb1efde1a569e52fc8d9", GitTreeState:"clean", BuildDate:"2018-12-16T04:30:10Z", GoVersion:"go1.10.3", Compiler:"gc", Platform:"linux/amd64"}