一、kubernetes常用命令
一、kubectl命令补全
1、master安装命令补全,并临时生效
1yum install -y bash-completion 2source /usr/share/bash-completion/bash_completion
2、永久生效
1source <(kubectl completion bash) 2echo "source <(kubectl completion bash)" >> ~/.bashrc
二、启动状态
1、master节点
11、更改配置文件,重新加载 2systemctl daemon-reload 3 42、启动master相关组件 5systemctl start kube-apiserver 6systemctl start kube-controller-manager 7systemctl start kube-scheduler 8 93、停止master相关组件 10systemctl stop kube-apiserver 11systemctl stop kube-controller-manager 12systemctl stop kube-scheduler 13 144、重启master相关组件 15systemctl restart kube-apiserver 16systemctl restart kube-controller-manager 17systemctl restart kube-scheduler 18 195、查看master相关组件状态 20systemctl status kube-apiserver 21systemctl status kube-controller-manager 22systemctl status kube-scheduler
2、etcd服务
11、更改配置后,重新加载 2systemctl daemon-reload 3 42、启动etcd服务 5systemctl start etcd.service 6 73、停止etcd服务 8systemctl stop etcd.service 9 104、重启etcd服务 11systemctl restart etcd.service 12 135、查看etcd服务状态 14systemctl status etcd.service
3、worker节点
11、更改配置后,重启加载 2systemctl daemon-reload 3 42、启动worker端相关组件 5systemctl start kube-proxy 6systemctl start docker 7systemctl start kubelet 8 93、停止worker端相关组件 10systemctl stop kube-proxy 11systemctl stop docker 12systemctl stop kubelet 13 144、重启worker端相关组件 15systemctl restart kube-proxy 16systemctl restart docker 17systemctl restart kubelet 18 195、查看worker端相关组件状态 20systemctl status kube-proxy 21systemctl status docker 22systemctl status kubelet
三、kubectl 常用命令操作
1、英文帮助信息
1、kubectl -h 查看具体操作参数
1kubectl controls the Kubernetes cluster manager. 2 3Find more information at https://github.com/kubernetes/kubernetes. 4 5Basic Commands (Beginner(初学者)): 6 create Create a resource from a file or from stdin. 7 expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service 8 run Run a particular image on the cluster 9 set Set specific features on objects 10 run-container Run a particular image on the cluster. This command is deprecated, use "run" instead 11 12Basic Commands (Intermediate(中级)): 13 get Display one or many resources 14 explain Documentation of resources 15 edit Edit a resource on the server 16 delete Delete resources by filenames, stdin, resources and names, or by resources and label selector 17 18Deploy Commands: 19 rollout Manage the rollout of a resource 20 rolling-update Perform a rolling update of the given ReplicationController 21 scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job 22 autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController 23 24Cluster Management Commands: 25 certificate Modify certificate resources. 26 cluster-info Display cluster info 27 top Display Resource (CPU/Memory/Storage) usage. 28 cordon Mark node as unschedulable 29 uncordon Mark node as schedulable 30 drain Drain node in preparation for maintenance 31 taint Update the taints on one or more nodes 32 33Troubleshooting and Debugging Commands: 34 describe Show details of a specific resource or group of resources 35 logs Print the logs for a container in a pod 36 attach Attach to a running container 37 exec Execute a command in a container 38 port-forward Forward one or more local ports to a pod 39 proxy Run a proxy to the Kubernetes API server 40 cp Copy files and directories to and from containers. 41 auth Inspect authorization 42 43Advanced Commands: 44 apply Apply a configuration to a resource by filename or stdin 45 patch Update field(s) of a resource using strategic merge patch 46 replace Replace a resource by filename or stdin 47 convert Convert config files between different API versions 48 49Settings Commands: 50 label Update the labels on a resource 51 annotate Update the annotations on a resource 52 completion Output shell completion code for the specified shell (bash or zsh) 53 54Other Commands: 55 api-versions Print the supported API versions on the server, in the form of "group/version" 56 config Modify kubeconfig files 57 help Help about any command 58 plugin Runs a command-line plugin 59 version Print the client and server version information 60 61Use "kubectl <command> --help" for more information about a given command. 62Use "kubectl options" for a list of global command-line options (applies to all commands).
2、kubectl可以操作的资源
1Display one or many resources 2 3Prints a table of the most important information about the specified resources. You can filter the list using a label 4selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current 5namespace unless you pass --all-namespaces. 6 7This command will hide resources that have completed, such as pods that are in the Succeeded or Failed phases. You can 8see the full results for any resource by providing the --show-all flag. Uninitialized objects are not shown unless 9--include-uninitialized is passed. 10 11By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter 12the attributes of the fetched resources. 13 14Valid resource types include: 15 16 * all 17 * certificatesigningrequests (aka 'csr') 18 * clusterrolebindings 19 * clusterroles 20 * componentstatuses (aka 'cs') 21 * configmaps (aka 'cm') 22 * controllerrevisions 23 * cronjobs 24 * customresourcedefinition (aka 'crd') 25 * daemonsets (aka 'ds') 26 * deployments (aka 'deploy') 27 * endpoints (aka 'ep') 28 * events (aka 'ev') 29 * horizontalpodautoscalers (aka 'hpa') 30 * ingresses (aka 'ing') 31 * jobs 32 * limitranges (aka 'limits') 33 * namespaces (aka 'ns') 34 * networkpolicies (aka 'netpol') 35 * nodes (aka 'no') 36 * persistentvolumeclaims (aka 'pvc') 37 * persistentvolumes (aka 'pv') 38 * poddisruptionbudgets (aka 'pdb') 39 * podpreset 40 * pods (aka 'po') 41 * podsecuritypolicies (aka 'psp') 42 * podtemplates 43 * replicasets (aka 'rs') 44 * replicationcontrollers (aka 'rc') 45 * resourcequotas (aka 'quota') 46 * rolebindings 47 * roles 48 * secrets 49 * serviceaccounts (aka 'sa') 50 * services (aka 'svc') 51 * statefulsets (aka 'sts') 52 * storageclasses (aka 'sc') 53 54Examples: 55 # List all pods in ps output format. 56 kubectl get pods 57 58 # List all pods in ps output format with more information (such as node name). 59 kubectl get pods -o wide 60 61 # List a single replication controller with specified NAME in ps output format. 62 kubectl get replicationcontroller web 63 64 # List a single pod in JSON output format. 65 kubectl get -o json pod web-pod-13je7 66 67 # List a pod identified by type and name specified in "pod.yaml" in JSON output format. 68 kubectl get -f pod.yaml -o json 69 70 # Return only the phase value of the specified pod. 71 kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}} 72 73 # List all replication controllers and services together in ps output format. 74 kubectl get rc,services 75 76 # List one or more resources by their type and names. 77 kubectl get rc/web service/frontend pods/web-pod-13je7 78 79 # List all resources with different types. 80 kubectl get all 81 82Options: 83 --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current 84context is ignored even if specified with --namespace. 85 --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in 86the template. Only applies to golang and jsonpath output formats. 87 --chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and 88may change in the future. 89 --export=false: If true, use 'export' for the resources. Exported resources are stripped of cluster-specific 90information. 91 --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector 92key1=value1,key2=value2). The server only supports a limited number of field queries per type. 93 -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server. 94 --ignore-not-found=false: If the requested object does not exist the command will return exit code 0. 95 --include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true] 96 --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to 97false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". 98Objects with empty metadata.initializers are regarded as initialized. 99 -L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are 100case-sensitive. You can also use multiple flag options like -L label1 -L label2... 101 --no-headers=false: When using the default or custom-column output format, don't print headers (default print 102headers). 103 -o, --output='': Output format. One of: 104json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... 105See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template 106[http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template 107[http://kubernetes.io/docs/user-guide/jsonpath]. 108 --raw='': Raw URI to request from the server. Uses the transport specified by the kubeconfig file. 109 -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage 110related manifests organized within the same directory. 111 -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) 112 -a, --show-all=false: When printing, show all resources (default hide terminated pods.) 113 --show-kind=false: If present, list the resource type for the requested object(s). 114 --show-labels=false: When printing, show all labels as the last column (default hide labels column) 115 --sort-by='': If non-empty, sort list types using this field specification. The field specification is expressed 116as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression 117must be an integer or a string. 118 --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The 119template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. 120 --use-openapi-print-columns=true: If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI 121schema for displaying a resource. 122 -w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded 123if no object name is provided. 124 --watch-only=false: Watch for changes to the requested object(s), without listing/getting first. 125 126Usage: 127 kubectl get 128[(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] 129(TYPE [NAME | -l label] | TYPE/NAME ...) [flags] [options] 130 131Use "kubectl options" for a list of global command-line options (applies to all commands).
3、获取具体操作的帮助信息
1Usage: 2 kubectl get 3[(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] 4(TYPE [NAME | -l label] | TYPE/NAME ...) [flags] [options]

1Examples: 2 # List all pods in ps output format. 3 kubectl get pods 4 5 # List all pods in ps output format with more information (such as node name). 6 kubectl get pods -o wide 7 8 # List a single replication controller with specified NAME in ps output format. 9 kubectl get replicationcontroller web 10 11 # List a single pod in JSON output format. 12 kubectl get -o json pod web-pod-13je7 13 14 # List a pod identified by type and name specified in "pod.yaml" in JSON output format. 15 kubectl get -f pod.yaml -o json 16 17 # Return only the phase value of the specified pod. 18 kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}} 19 20 # List all replication controllers and services together in ps output format. 21 kubectl get rc,services 22 23 # List one or more resources by their type and names. 24 kubectl get rc/web service/frontend pods/web-pod-13je7 25 26 # List all resources with different types. 27 kubectl get all 28 29Options: 30 --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current 31context is ignored even if specified with --namespace. 32 --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in 33the template. Only applies to golang and jsonpath output formats. 34 --chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and 35may change in the future. 36 --export=false: If true, use 'export' for the resources. Exported resources are stripped of cluster-specific 37information. 38 --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector 39key1=value1,key2=value2). The server only supports a limited number of field queries per type. 40 -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server. 41 --ignore-not-found=false: If the requested object does not exist the command will return exit code 0. 42 --include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true] 43 --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to 44false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". 45Objects with empty metadata.initializers are regarded as initialized. 46 -L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are 47case-sensitive. You can also use multiple flag options like -L label1 -L label2... 48 --no-headers=false: When using the default or custom-column output format, don't print headers (default print 49headers). 50 -o, --output='': Output format. One of: 51json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... 52See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template 53[http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template 54[http://kubernetes.io/docs/user-guide/jsonpath]. 55 --raw='': Raw URI to request from the server. Uses the transport specified by the kubeconfig file. 56 -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage 57related manifests organized within the same directory. 58 -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) 59 -a, --show-all=false: When printing, show all resources (default hide terminated pods.) 60 --show-kind=false: If present, list the resource type for the requested object(s). 61 --show-labels=false: When printing, show all labels as the last column (default hide labels column) 62 --sort-by='': If non-empty, sort list types using this field specification. The field specification is expressed 63as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression 64must be an integer or a string. 65 --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The 66template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. 67 --use-openapi-print-columns=true: If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI 68schema for displaying a resource. 69 -w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded 70if no object name is provided. 71 --watch-only=false: Watch for changes to the requested object(s), without listing/getting first. 72 73Usage: 74 kubectl get 75[(-o|--output=)json|yaml|wide|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=...] 76(TYPE [NAME | -l label] | TYPE/NAME ...) [flags] [options] 77 78Use "kubectl options" for a list of global command-line options (applies to all commands).
具体操作的帮助文档
2、查看类命令
1、获取节点相应服务的信息:kubectl get nodes
kubectl get pods
按selector名来查找pod
kubectl get pod --selector name=redis
2、查看集群信息
kubectl cluster-info
3、查看各组件信息
kubectl -s http://localhost:8080 get componentstatuses
4、查看pods所在的运行节点
kubectl get pods -o wide
5、查看pods定义的详细信息
kubectl get pods -o yaml
6、查看运行的pod的环境变量
kubectl exec pod名 env
7、查看指定pod的日志
kubectl logs -f pods/heapster-xxxxx -n kube-system
3、操作类命令
1、创建资源
kubectl create -f 文件名.yaml
2、重建资源
kubectl replace -f 文件名 [--force]
3、删除资源
1kubectl delete -f 文件名 2kubectl delete pod pod名 3kubectl delete rc rc名 4kubectl delete service service名 5kubectl delete pod --all
四、kubectl进阶命令操作
1、kubectl get:获取指定资源的基本信息
11 kubectl get services kubernetes-dashboard -n kube-system #查看所有service 22 kubectl get deployment kubernetes-dashboard -n kube-system #查看所有发布 33 kubectl get pods --all-namespaces #查看所有pod 44 kubectl get pods -o wide --all-namespaces #查看所有pod的IP及节点 55 kubectl get pods -n kube-system | grep dashboard 66 kubectl get nodes -lzone #获取zone的节点
2、kubectl describe:查看指定资源详细描述信息
11 kubectl describe service/kubernetes-dashboard --namespace="kube-system" 22 kubectl describe pods/kubernetes-dashboard-349859023-g6q8c --namespace="kube-system" #指定类型查看 33 kubectl describe pod nginx-772ai #查看pod详细信息
3、kubectl scale:动态伸缩
11 kubectl scale rc nginx --replicas=5 # 动态伸缩 22 kubectl scale deployment redis-slave --replicas=5 #动态伸缩 33 kubectl scale --replicas=2 -f redis-slave-deployment.yaml #动态伸缩
4、kubectl exec:进入pod启动的容器
1 kubectl exec -it redis-master-1033017107-q47hh /bin/bash #进入容器
5、kubectl label:添加label值
11 kubectl label nodes node1 zone=north #增加节点lable值 spec.nodeSelector: zone: north #指定pod在哪个节点 22 kubectl label pod redis-master-1033017107-q47hh role=master #增加lable值 [key]=[value] 33 kubectl label pod redis-master-1033017107-q47hh role- #删除lable值 44 kubectl label pod redis-master-1033017107-q47hh role=backend --overwrite #修改lable值
6、kubectl rolling-update:滚动升级
11 kubectl rolling-update redis-master -f redis-master-controller-v2.yaml #配置文件滚动升级 22 kubectl rolling-update redis-master --image=redis-master:2.0 #命令升级 33 kubectl rolling-update redis-master --image=redis-master:1.0 --rollback #pod版本回滚
五、etcdctl 常用操作
11 etcdctl cluster-health #检查网络集群健康状态 22 etcdctl --endpoints=https://192.168.71.221:2379 cluster-health #带有安全认证检查网络集群健康状态 33 etcdctl member list 44 etcdctl set /k8s/network/config '{ "Network": "10.1.0.0/16" }' 55 etcdctl get /k8s/network/config