K8s常用命令操作
一、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).
k8s拷贝文件
从pod中拷贝到k8s节点上 kubecet cp pod-name:/path/to/file /tmp/localpath/file
kubectl create / replace 与kubectl apply 的区别
- kubectl replace 的执行过程,是使用新的 YAML 文件中的 API 对象,替换原有的 API 对象
- kubectl apply,则是执行了一个对原有 API 对象的 PATCH 操作。
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
查看之前的容器日志(容器不断重启)
kubectl logs --previous pod-name
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
4、node节点操作
1、不可调度(打污点),驱逐pod,恢复调度
不允许pod调度到此node,对正在运行的pod不会驱逐
kubectl cordon node1
节点排水驱n2 node所有pod忽略daemoset
kubectl drain node1 --delete-local-data=true --ignore-daemonsets=true --force
恢复调度
kubectl uncordon node1
2、标签操作
查看node标签 kubectl get nodes --show-labels 添加node节点标签 kubectl label nodes node1 disktype=ssd 删除节点标签 kubectl label nodes node1 disktype-
5、deployment版本管理
命令更新deploy image版本 kubectl set image deploy busybox busybox=harbor.cluster.com:6666/rancher/busybox:v2 回退上个版本 kubectl rollout undo deployment/busybox kubectl rollout status deployment/busybox 查看历史版本记录 kubectl rollout history deploy/busybox --revision=5 查看历史版本详细信息 kubectl rollout history deploy/busybox --revision=5 REVISION CHANGE-CAUSE 1 <none> 2 <none> 4 <none> 5 <none 回滚到指定的版本 kubectl rollout undo deployment/busybox --to-revision=2
四)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版本回滚
7、kubectl config:切换默认的操作的namespace
kubernetes默认操作的ns是default。将默认操作的ns设置为kube-system
# kubectl config set-context --current --namespace=kube-system Context "kubernetes-admin@kubernetes" modified.
获取当前ns的pod
# kubectl get po NAME READY STATUS RESTARTS AGE coredns-65c54cc984-5fms8 1/1 Running 0 210d coredns-65c54cc984-cq25j 1/1 Running 0 210d etcd-l-k8s-master-01 1/1 Running 0 210d kube-apiserver-l-k8s-master-01 1/1 Running 0 204d kube-controller-manager-l-k8s-master-01 1/1 Running 0 210d kube-proxy-8wdcj 1/1 Running 0 210d kube-proxy-ccn9w 1/1 Running 0 210d kube-scheduler-l-k8s-master-01 1/1 Running 0 210d snapshot-controller-0 1/1 Running 0 209d
五)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