本文对kubectl命令进行研究,掌握常用的kubectl命令。参见文档kubectl命令表。
语法:
kubectl [command] [TYPE] [NAME] [flags] -o=<output_format>
- command: 表示要执行的操作,如:create, get, describe, delete。
- TYPE:表示操作的资源类型,大小写不敏感,可以指定单数、复数或缩写。
- NAME:指定resource的name,大小写敏感,不指定的话,针对所有。
output format:
-o=json 输出JSON格式的API对象。
-o=name 仅打印资源名称,而不打印其他内容。
-o=wide 以纯文本格式输出任何附加信息。对于pod,包括node名称。
-o=yaml 输出YAML格式的API对象。
command:
![3bff6e079dadce7f510af93727a69990.png](https://i-blog.csdnimg.cn/blog_migrate/19fae4da7533b93e9691197fabd8d73d.jpeg)
![3bff6e079dadce7f510af93727a69990.png](https://i-blog.csdnimg.cn/blog_migrate/19fae4da7533b93e9691197fabd8d73d.jpeg)
TYPE:
![d7899746cb83fd6199956f8ced362588.png](https://i-blog.csdnimg.cn/blog_migrate/4180b8778a4e95013cd63d61635db4f0.jpeg)
![962bd6c5cbd4c01b56d55772315c6ca1.png](https://i-blog.csdnimg.cn/blog_migrate/d4b03fd0cc00396b02d11d699e8ab906.jpeg)
暂记:
// Create a replication controller using the definition in example-controller.yaml.
$ kubectl create -f example-controller.yaml
// Create the objects that are defined in any .yaml, .yml, or .json file within the <directory> directory.
$ kubectl create -f <directory>
// Display the details of all the pods that are managed by the replication controller named <rc-name>.
// Remember: Any pods that are created by the replication controller get prefixed with the name of the replication controller.
$ kubectl describe pods <rc-name>
// Start streaming the logs from pod <pod-name>. This is similar to the 'tail -f' Linux command.
$ kubectl logs -f <pod-name>
Kubectl plugins
kubectl plugin用来封装复杂的kubectl命令,可以是任何语言创建的可执行程序,以kubectl-为前缀命名。
下面是一个简单的kubectl plugin,用来输出“Hello World”。删除可执行程序便卸载plugin。
# create a simple plugin in any language and name the resulting executable file
# so that it begins with the prefix "kubectl-"
cat ./kubectl-hello
#!/bin/bash
# this plugin prints the words "hello world"
echo "hello world"
# with our plugin written, let's make it executable
sudo chmod +x ./kubectl-hello
# and move it to a location in our PATH
sudo mv ./kubectl-hello /usr/local/bin
# we have now created and "installed" a kubectl plugin.
# we can begin using our plugin by invoking it from kubectl as if it were a regular command
kubectl hello
使用下面命令可查看所有plugin。
kubectl plugin list
Kubectl与docker关系
-docker run
执行image
$ docker run -d --restart=always -e DOMAIN=cluster --name nginx-app -p 80:80 nginx
a9ec34d9878748d2f33dc20cb25c714ff21da8d40558b45bfaec9955859075d0
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9ec34d98787 nginx "nginx -g 'daemon of 2 seconds ago Up 2 seconds 0.0.0.0:80->80/tcp, 443/tcp nginx-app
kubectl方式:
# start the pod running nginx
$ kubectl run --image=nginx nginx-app --port=80 --env="DOMAIN=cluster"
deployment "nginx-app" created
可以使用上面创建的deployment暴露一个service:
# expose a port through with a service
$ kubectl expose deployment nginx-app --port=80 --name=nginx-http
service "nginx-http" exposed
-docker ps
查看当前运行的container
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9ec34d98787 nginx "nginx -g 'daemon of About an hour ago Up About an hour 0.0.0.0:80->80/tcp, 443/tcp nginx-app
kubectl:
$ kubectl get po
NAME READY STATUS RESTARTS AGE
nginx-app-5jyvm 1/1 Running 0 1h
-docker attach
连接已经运行在容器中的进程
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9ec34d98787 nginx "nginx -g 'daemon of 8 minutes ago Up 8 minutes 0.0.0.0:80->80/tcp, 443/tcp nginx-app
$ docker attach a9ec34d98787
...
kubectl:
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-app-5jyvm 1/1 Running 0 10m
$ kubectl attach -it nginx-app-5jyvm
...
-docker exec
在容器中执行命令
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9ec34d98787 nginx "nginx -g 'daemon of 8 minutes ago Up 8 minutes 0.0.0.0:80->80/tcp, 443/tcp nginx-app
$ docker exec a9ec34d98787 cat /etc/hostname
a9ec34d98787
#交互式
$ docker exec -ti a9ec34d98787 /bin/sh
# exit
kubectl:
$ kubectl get po
NAME READY STATUS RESTARTS AGE
nginx-app-5jyvm 1/1 Running 0 10m
$ kubectl exec nginx-app-5jyvm -- cat /etc/hostname
nginx-app-5jyvm
#交互式
$ kubectl exec -ti nginx-app-5jyvm -- /bin/sh
# exit
-docker logs
用来打印容器内日志
$ docker logs -f a9e
192.168.9.1 - - [14/Jul/2015:01:04:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.35.0" "-"
192.168.9.1 - - [14/Jul/2015:01:04:03 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.35.0" "-"
kubectl:
$ kubectl logs -f nginx-app-zibvs
10.240.63.110 - - [14/Jul/2015:01:09:01 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
10.240.63.110 - - [14/Jul/2015:01:09:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
#查看以前在kubernetes中的日志
$ kubectl logs --previous nginx-app-zibvs
10.240.63.110 - - [14/Jul/2015:01:09:01 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
10.240.63.110 - - [14/Jul/2015:01:09:02 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.26.0" "-"
-docker stop & docker rm
停止和删除正在运行的进程
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a9ec34d98787 nginx "nginx -g 'daemon of 22 hours ago Up 22 hours 0.0.0.0:80->80/tcp, 443/tcp nginx-app
$ docker stop a9ec34d98787
a9ec34d98787
$ docker rm a9ec34d98787
a9ec34d98787
kubectl:
$ kubectl get deployment nginx-app
NAME DESIRED CURRENT UP-TO-DATE AVAILABLE AGE
nginx-app 1 1 1 1 2m
$ kubectl get po -l run=nginx-app
NAME READY STATUS RESTARTS AGE
nginx-app-2883164633-aklf7 1/1 Running 0 2m
$ kubectl delete deployment nginx-app
deployment "nginx-app" deleted
$ kubectl get po -l run=nginx-app
# Return nothing
kubectl命令
-kubectl create
从文件或stdin来创建resource,格式可以为YAML或JSON。可以创建很多种resource,详情参见create.
示例:
kubectl create -f ./pod.json
cat pod.json | kubectl create -f -
kubectl create -f docker-registry.yaml --edit -o json
clusterrole/clusterrolebinding/role/rolebinding/serviceaccount
kubectl create clusterrole pod-reader --verb=get,list,watch --resource=pods
kubectl create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --group=group1
kubectl create role foo --verb=get,list,watch --resource=pods,pods/status
kubectl create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1
kubectl create serviceaccount my-service-account
object
$ cronjob NAME --image=image --schedule='0/5 * * * ?' -- [COMMAND] [args...]
kubectl create cronjob test-job --image=busybox --schedule="*/1 * * * *" -- date
$ job NAME --image=image [--from=cronjob/name] -- [COMMAND] [args...]
kubectl create job my-job --image=busybox -- date
$ deployment NAME --image=image [--dry-run]
kubectl create deployment my-dep --image=busybox
$ configmap NAME [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run]
kubectl create configmap my-config --from-file=path/to/bar
kubectl create namespace my-namespace
$ priorityclass NAME --value=VALUE --global-default=BOOL [--dry-run]
kubectl create priorityclass default-priority --value=1000 --global-default=true --description="default priority"
kubectl create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER
--docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
kubectl create secret generic my-secret --from-file=path/to/bar
kubectl create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key
kubectl create service clusterip my-cs --tcp=5678:8080
#对于headless service(no balancing),设置clusterip为None
kubectl create service clusterip my-cs --clusterip="None"
kubectl create service externalname my-ns --external-name bar.com
kubectl create service loadbalancer my-lbs --tcp=5678:8080
kubectl create service nodeport my-ns --tcp=5678:8080
-kubectl get
默认获取当前namespace的资源信息,若需要获取特定namespace中的资源信息,需要指定namespace。指定--all-namespaces可以获取所有namespace上的资源。也可以使用--selector进行过滤具有特定label的资源。
kubectl get pods -o wide
kubectl get rc,services
kubectl get rc/web service/frontend pods/web-pod-13je7
-kubectl run
创建并运行一个或多个容器镜像,并创建deployment或job来管理容器。
语法:
$ run NAME --image=image [--env="key=value"] [--port=port] [--replicas=replicas] [--dry-run=bool]
[--overrides=inline-json] [--command] -- [COMMAND] [args...]
其他参数:
limits:用来限制容器使用的资源,如:'cpu=200m,memory=512Mi'
requests:容器需要的资源数量,如:'cpu=100m,memory=256Mi'
port:容器暴露的端口号,如果--expose为true,创建的service将使用该端口号
restart:可选值[Always, OnFailure, Never],默认为Always,若为Always将创建deployment,若为OnFailure将创建job,若为Never将创建pod。
stdin:保留pod中的container的stdin开放
tty:为pod中每个container都关联一个tty
rm: 删除该命令创建的容器资源
schedule: schedule job in cron format
示例:
kubectl run hazelcast --image=hazelcast --env="DNS_DOMAIN=cluster" --env="POD_NAMESPACE=default"
kubectl run hazelcast --image=hazelcast --labels="app=hazelcast,env=prod"
kubectl run nginx --image=nginx --replicas=5
kubectl run hazelcast --image=hazelcast --port=5701
-kubectl expose
将资源暴露为新的Kubernetes Service,资源包括pod(po),service(svc),replication controller(rc),deployment(deploy),replica set(rs)。
语法:
$ expose (-f FILENAME | TYPE NAME) [--port=port] [--protocol=TCP|UDP] [--target-port=number-or-name] [--name=name]
[--external-ip=external-ip-of-service] [--type=type]
cluster-ip: 指定分配给service的cluster ip,如果不指定则自动分配,若指定为None,则创建headless service。
port: service使用的端口号,若不指定,使用resource暴露的端口号
target-port:service将转流的容器端口
selector:service使用的label selector,若不指定,从resource中推断selector,只支持等号类型的selector
type: service的类型:ClusterIP, NodePort, or LoadBalancer. Default is 'ClusterIP'.
示例:
kubectl expose rc nginx --port=80 --target-port=8000
kubectl expose pod valid-pod --port=444 --name=frontend
kubectl expose service nginx --port=443 --target-port=8443 --name=nginx-https
-kubectl delete
通过配置文件名、stdin、资源名称或label选择器来删除资源。
注意:执行delete命令时不会检查资源版本,如果在执行delete操作时有人进行了更新操作,那么更新操作将连同资源一起被删除。
语法:
$ delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])
示例:
#删除名为“baz”和“foo”的Pod和Service
kubectl delete pod,service baz foo
#删除 Label name = myLabel的pod和Service
kubectl delete pods,services -l name=myLabel
#强制删除dead node上的pod
kubectl delete pod foo --grace-period=0 --force
#删除所有pod
kubectl delete pods --all
-kubectl annotate
用来更新一个或多个资源的annotations。所有的k8s资源都支持使用annotation来存放额外的数据。 Annotation为key/value对,可以存放任意string值,比label大。若annotation已经存在,更新需要指定--overwrite。
语法:
$ annotate [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
示例:
kubectl annotate pods foo description='my frontend'
kubectl annotate --overwrite pods foo description='my frontend running nginx'
#删除名称为description的annotation
kubectl annotate pods foo description-
-kubectl autoscale
作用于Deployment, ReplicaSet, StatefulSet, or ReplicationController,用于创建auto scaler来自动管理pod数量。
语法:
$ autoscale (-f FILENAME | TYPE NAME | TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU]
示例:
kubectl autoscale deployment foo --min=2 --max=10
kubectl autoscale rc foo --max=5 --cpu-percent=80
-kubectl diff
将当前运行中配置与文件中提供配置进行比较。
语法:
$ diff -f FILENAME
示例:
kubectl diff -f pod.json
-kubectl edit
使用默认编辑器 编辑服务器上定义的资源,将使用环境变量KUBE_EDITOR或EDITOR定义的编译器,或者直接使用vi(linux)或notebook(windows)。默认的格式为YAML,可以使用-o json来使用json格式。
语法:
$ edit (RESOURCE/NAME | -f FILENAME)
示例:
kubectl edit svc/docker-registry
-kubectl label
用来更新资源的label。若要更新已有的label,使用--overwrite。
语法:
$ label [--overwrite] (-f FILENAME | TYPE NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--resource-version=version]
示例:
kubectl label pods foo unhealthy=true
kubectl label --overwrite pods foo status=unhealthy
#更新namespace中的所有pod
kubectl label pods --all status=unhealthy
-kubectl patch
更新resource field,使用strategic merge patch, a JSON merge patch, or a JSON patch。可以使用JSON或YAML格式。
语法:
$ patch (-f FILENAME | TYPE NAME) -p PATCH
示例:
#使用strategic merge patch,JSON格式
kubectl patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
#使用strategic merge patch,YAML格式
kubectl patch node k8s-node-1 -p $'spec:n unschedulable: true'
-kubectl replace
替换资源,若资源已经存在,则需要指定完整的resource spec。
语法:
$ replace -f FILENAME
示例:
kubectl replace -f ./pod.json
-kubectl rollout
管理资源的rollout,可操作资源包括deployments,daemonsets,statefulsets。
示例:
#暂停deployment,使用kubectl rollout resume来恢复,目前只支持deployment
kubectl rollout pause deployment/nginx
#恢复暂停的资源
kubectl rollout resume deployment/nginx
#重启资源
kubectl rollout restart deployment/nginx
#rollback到上一次,可指定--to-revision,默认为0
kubectl rollout undo deployment/abc
-kubectl scale
设置资源的大小,支持Deployment, ReplicaSet, Replication Controller, or StatefulSet.可以指定条件,条件满足才会scale。
语法:
$ scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)
示例:
kubectl scale --replicas=3 rs/foo
kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
-kubectl set
更新资源的配置信息,包括env,resources, image, selector, serviceaccount,subject。
示例:
kubectl set env deployment/registry STORAGE_DIR=/local
kubectl set image deployments,rc nginx=nginx:1.9.1 --all
kubectl set resources deployment nginx --limits=cpu=200m,memory=512Mi --requests=cpu=100m,memory=256Mi
kubectl set serviceaccount deployment nginx-deployment serviceaccount1
-kubectl cp
在local和container之间拷贝文件或目录。
示例:
kubectl cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
kubectl cp <some-namespace>/<some-pod>:/tmp/foo /tmp/bar
-kubectl get
列出一个或多个资源的信息
语法:
$ get [(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...
|jsonpath=...|jsonpath-file=...] (TYPE [NAME | -l label] | TYPE/NAME ...) [flags]
示例:
#列出Pod以及运行Pod节点信息
kubectl get pods -o wide
#List all replication controllers and services together in plain-text output format.
$ kubectl get rc,services
-kubectl describe
用来展示资源的详情。
语法:
$ describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME)
示例:
kubectl describe nodes kubernetes-node-emt8.c.myproject.internal
kubectl describe pods/nginx
kubectl describe po -l name=myLabel
-kubectl exec
在容器中执行命令。
语法:
$ exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...]
示例:
kubectl exec mypod date
kubectl exec mypod -c ruby-container -i -t -- bash -il
-kubectl logs
用来获取容器中的日志。
语法:
$ logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER]
示例:
kubectl logs nginx
kubectl logs -f -c ruby web-1
kubectl logs --tail=20 nginx
kubectl logs --since=1h nginx
-kubectl top
Display Resource (CPU/Memory/Storage) usage.
示例:
kubectl top node
kubectl top node NODE_NAME
kubectl top pod
kubectl top pod --namespace=NAMESPACE
kubectl top pod POD_NAME --containers