一、kubernetes常用命令
一、kubectl命令補全
1、master安裝命令補全,並臨時生效
yum install -y bash-completion source /usr/share/bash-completion/bash_completion
2、永久生效
source <(kubectl completion bash) echo "source <(kubectl completion bash)" >> ~/.bashrc
二、啟動狀態
1、master節點
1、更改配置文件,重新加載 systemctl daemon-reload 2、啟動master相關組件 systemctl start kube-apiserver systemctl start kube-controller-manager systemctl start kube-scheduler 3、停止master相關組件 systemctl stop kube-apiserver systemctl stop kube-controller-manager systemctl stop kube-scheduler 4、重啟master相關組件 systemctl restart kube-apiserver systemctl restart kube-controller-manager systemctl restart kube-scheduler 5、查看master相關組件狀態 systemctl status kube-apiserver systemctl status kube-controller-manager systemctl status kube-scheduler
2、etcd服務
1、更改配置后,重新加載 systemctl daemon-reload 2、啟動etcd服務 systemctl start etcd.service 3、停止etcd服務 systemctl stop etcd.service 4、重啟etcd服務 systemctl restart etcd.service 5、查看etcd服務狀態 systemctl status etcd.service
3、worker節點
1、更改配置后,重啟加載 systemctl daemon-reload 2、啟動worker端相關組件 systemctl start kube-proxy systemctl start docker systemctl start kubelet 3、停止worker端相關組件 systemctl stop kube-proxy systemctl stop docker systemctl stop kubelet 4、重啟worker端相關組件 systemctl restart kube-proxy systemctl restart docker systemctl restart kubelet 5、查看worker端相關組件狀態 systemctl status kube-proxy systemctl status docker systemctl status kubelet
三、kubectl 常用命令操作
1、英文幫助信息
1、kubectl -h 查看具體操作參數
kubectl controls the Kubernetes cluster manager. Find more information at https://github.com/kubernetes/kubernetes. Basic Commands (Beginner(初學者)): create Create a resource from a file or from stdin. expose Take a replication controller, service, deployment or pod and expose it as a new Kubernetes Service run Run a particular image on the cluster set Set specific features on objects run-container Run a particular image on the cluster. This command is deprecated, use "run" instead Basic Commands (Intermediate(中級)): get Display one or many resources explain Documentation of resources edit Edit a resource on the server delete Delete resources by filenames, stdin, resources and names, or by resources and label selector Deploy Commands: rollout Manage the rollout of a resource rolling-update Perform a rolling update of the given ReplicationController scale Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job autoscale Auto-scale a Deployment, ReplicaSet, or ReplicationController Cluster Management Commands: certificate Modify certificate resources. cluster-info Display cluster info top Display Resource (CPU/Memory/Storage) usage. cordon Mark node as unschedulable uncordon Mark node as schedulable drain Drain node in preparation for maintenance taint Update the taints on one or more nodes Troubleshooting and Debugging Commands: describe Show details of a specific resource or group of resources logs Print the logs for a container in a pod attach Attach to a running container exec Execute a command in a container port-forward Forward one or more local ports to a pod proxy Run a proxy to the Kubernetes API server cp Copy files and directories to and from containers. auth Inspect authorization Advanced Commands: apply Apply a configuration to a resource by filename or stdin patch Update field(s) of a resource using strategic merge patch replace Replace a resource by filename or stdin convert Convert config files between different API versions Settings Commands: label Update the labels on a resource annotate Update the annotations on a resource completion Output shell completion code for the specified shell (bash or zsh) Other Commands: api-versions Print the supported API versions on the server, in the form of "group/version" config Modify kubeconfig files help Help about any command plugin Runs a command-line plugin version Print the client and server version information Use "kubectl <command> --help" for more information about a given command. Use "kubectl options" for a list of global command-line options (applies to all commands).
2、kubectl可以操作的資源
Display one or many resources Prints a table of the most important information about the specified resources. You can filter the list using a label selector and the --selector flag. If the desired resource type is namespaced you will only see results in your current namespace unless you pass --all-namespaces. This command will hide resources that have completed, such as pods that are in the Succeeded or Failed phases. You can see the full results for any resource by providing the --show-all flag. Uninitialized objects are not shown unless --include-uninitialized is passed. By specifying the output as 'template' and providing a Go template as the value of the --template flag, you can filter the attributes of the fetched resources. Valid resource types include: * all * certificatesigningrequests (aka 'csr') * clusterrolebindings * clusterroles * componentstatuses (aka 'cs') * configmaps (aka 'cm') * controllerrevisions * cronjobs * customresourcedefinition (aka 'crd') * daemonsets (aka 'ds') * deployments (aka 'deploy') * endpoints (aka 'ep') * events (aka 'ev') * horizontalpodautoscalers (aka 'hpa') * ingresses (aka 'ing') * jobs * limitranges (aka 'limits') * namespaces (aka 'ns') * networkpolicies (aka 'netpol') * nodes (aka 'no') * persistentvolumeclaims (aka 'pvc') * persistentvolumes (aka 'pv') * poddisruptionbudgets (aka 'pdb') * podpreset * pods (aka 'po') * podsecuritypolicies (aka 'psp') * podtemplates * replicasets (aka 'rs') * replicationcontrollers (aka 'rc') * resourcequotas (aka 'quota') * rolebindings * roles * secrets * serviceaccounts (aka 'sa') * services (aka 'svc') * statefulsets (aka 'sts') * storageclasses (aka 'sc') Examples: # List all pods in ps output format. kubectl get pods # List all pods in ps output format with more information (such as node name). kubectl get pods -o wide # List a single replication controller with specified NAME in ps output format. kubectl get replicationcontroller web # List a single pod in JSON output format. kubectl get -o json pod web-pod-13je7 # List a pod identified by type and name specified in "pod.yaml" in JSON output format. kubectl get -f pod.yaml -o json # Return only the phase value of the specified pod. kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}} # List all replication controllers and services together in ps output format. kubectl get rc,services # List one or more resources by their type and names. kubectl get rc/web service/frontend pods/web-pod-13je7 # List all resources with different types. kubectl get all Options: --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. --chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. --export=false: If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server. --ignore-not-found=false: If the requested object does not exist the command will return exit code 0. --include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true] --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized. -L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag options like -L label1 -L label2... --no-headers=false: When using the default or custom-column output format, don't print headers (default print headers). -o, --output='': Output format. One of: json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath]. --raw='': Raw URI to request from the server. Uses the transport specified by the kubeconfig file. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) -a, --show-all=false: When printing, show all resources (default hide terminated pods.) --show-kind=false: If present, list the resource type for the requested object(s). --show-labels=false: When printing, show all labels as the last column (default hide labels column) --sort-by='': If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string. --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. --use-openapi-print-columns=true: If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource. -w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded if no object name is provided. --watch-only=false: Watch for changes to the requested object(s), without listing/getting first. Usage: kubectl 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] [options] Use "kubectl options" for a list of global command-line options (applies to all commands).
3、獲取具體操作的幫助信息
Usage: kubectl 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] [options]
Examples: # List all pods in ps output format. kubectl get pods # List all pods in ps output format with more information (such as node name). kubectl get pods -o wide # List a single replication controller with specified NAME in ps output format. kubectl get replicationcontroller web # List a single pod in JSON output format. kubectl get -o json pod web-pod-13je7 # List a pod identified by type and name specified in "pod.yaml" in JSON output format. kubectl get -f pod.yaml -o json # Return only the phase value of the specified pod. kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}} # List all replication controllers and services together in ps output format. kubectl get rc,services # List one or more resources by their type and names. kubectl get rc/web service/frontend pods/web-pod-13je7 # List all resources with different types. kubectl get all Options: --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current context is ignored even if specified with --namespace. --allow-missing-template-keys=true: If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. --chunk-size=500: Return large lists in chunks rather than all at once. Pass 0 to disable. This flag is beta and may change in the future. --export=false: If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. --field-selector='': Selector (field query) to filter on, supports '=', '==', and '!='.(e.g. --field-selector key1=value1,key2=value2). The server only supports a limited number of field queries per type. -f, --filename=[]: Filename, directory, or URL to files identifying the resource to get from a server. --ignore-not-found=false: If the requested object does not exist the command will return exit code 0. --include-extended-apis=true: If true, include definitions of new APIs via calls to the API server. [default true] --include-uninitialized=false: If true, the kubectl command applies to uninitialized objects. If explicitly set to false, this flag overrides other flags that make the kubectl commands apply to uninitialized objects, e.g., "--all". Objects with empty metadata.initializers are regarded as initialized. -L, --label-columns=[]: Accepts a comma separated list of labels that are going to be presented as columns. Names are case-sensitive. You can also use multiple flag options like -L label1 -L label2... --no-headers=false: When using the default or custom-column output format, don't print headers (default print headers). -o, --output='': Output format. One of: json|yaml|wide|name|custom-columns=...|custom-columns-file=...|go-template=...|go-template-file=...|jsonpath=...|jsonpath-file=... See custom columns [http://kubernetes.io/docs/user-guide/kubectl-overview/#custom-columns], golang template [http://golang.org/pkg/text/template/#pkg-overview] and jsonpath template [http://kubernetes.io/docs/user-guide/jsonpath]. --raw='': Raw URI to request from the server. Uses the transport specified by the kubeconfig file. -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2) -a, --show-all=false: When printing, show all resources (default hide terminated pods.) --show-kind=false: If present, list the resource type for the requested object(s). --show-labels=false: When printing, show all labels as the last column (default hide labels column) --sort-by='': If non-empty, sort list types using this field specification. The field specification is expressed as a JSONPath expression (e.g. '{.metadata.name}'). The field in the API resource specified by this JSONPath expression must be an integer or a string. --template='': Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview]. --use-openapi-print-columns=true: If true, use x-kubernetes-print-column metadata (if present) from the OpenAPI schema for displaying a resource. -w, --watch=false: After listing/getting the requested object, watch for changes. Uninitialized objects are excluded if no object name is provided. --watch-only=false: Watch for changes to the requested object(s), without listing/getting first. Usage: kubectl 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] [options] Use "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、刪除資源
kubectl delete -f 文件名
kubectl delete pod pod名
kubectl delete rc rc名
kubectl delete service service名
kubectl delete pod --all
四、kubectl進階命令操作
1、kubectl get:獲取指定資源的基本信息
1 kubectl get services kubernetes-dashboard -n kube-system #查看所有service 2 kubectl get deployment kubernetes-dashboard -n kube-system #查看所有發布 3 kubectl get pods --all-namespaces #查看所有pod 4 kubectl get pods -o wide --all-namespaces #查看所有pod的IP及節點 5 kubectl get pods -n kube-system | grep dashboard 6 kubectl get nodes -lzone #獲取zone的節點
2、kubectl describe:查看指定資源詳細描述信息
1 kubectl describe service/kubernetes-dashboard --namespace="kube-system" 2 kubectl describe pods/kubernetes-dashboard-349859023-g6q8c --namespace="kube-system" #指定類型查看 3 kubectl describe pod nginx-772ai #查看pod詳細信息
3、kubectl scale:動態伸縮
1 kubectl scale rc nginx --replicas=5 # 動態伸縮 2 kubectl scale deployment redis-slave --replicas=5 #動態伸縮 3 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值
1 kubectl label nodes node1 zone=north #增加節點lable值 spec.nodeSelector: zone: north #指定pod在哪個節點 2 kubectl label pod redis-master-1033017107-q47hh role=master #增加lable值 [key]=[value] 3 kubectl label pod redis-master-1033017107-q47hh role- #刪除lable值 4 kubectl label pod redis-master-1033017107-q47hh role=backend --overwrite #修改lable值
6、kubectl rolling-update:滾動升級
1 kubectl rolling-update redis-master -f redis-master-controller-v2.yaml #配置文件滾動升級 2 kubectl rolling-update redis-master --image=redis-master:2.0 #命令升級 3 kubectl rolling-update redis-master --image=redis-master:1.0 --rollback #pod版本回滾
五、etcdctl 常用操作
1 etcdctl cluster-health #檢查網絡集群健康狀態 2 etcdctl --endpoints=https://192.168.71.221:2379 cluster-health #帶有安全認證檢查網絡集群健康狀態 3 etcdctl member list 4 etcdctl set /k8s/network/config '{ "Network": "10.1.0.0/16" }' 5 etcdctl get /k8s/network/config
