目录
- kubectl 文档
- 资源类型
- 格式化输出
- 语法
- kubectl 常用命令(K8S)
- kubectl 命令(K8S)
- kubectl delete
- kubectl replace
kubectl 文档
https://kubernetes.io/zh/docs/reference/kubectl/overview/
资源类型
https://kubernetes.io/zh/docs/reference/kubectl/overview/#资源类型
格式化输出
https://kubernetes.io/zh/docs/reference/kubectl/overview/
所有
kubectl
命令的默认输出格式都是人类可读的纯文本格式。要以特定格式向终端窗口输出详细信息,可以将-o
或--output
参数添加到受支持的kubectl
命令中。
语法
kubectl [command] [TYPE] [NAME] -o=<output_format>
根据 kubectl
操作,支持以下输出格式:
Output format | Description |
---|---|
-o custom-columns= |
使用逗号分隔的自定义列列表打印表。 |
-o custom-columns-file= |
使用 `` 文件中的自定义列模板打印表。 |
-o json |
输出 JSON 格式的 API 对象 |
-o jsonpath= |
打印 jsonpath 表达式定义的字段 |
-o jsonpath-file= |
打印 `` 文件中 jsonpath 表达式定义的字段。 |
-o name |
仅打印资源名称而不打印任何其他内容。 |
-o wide |
以纯文本格式输出,包含任何附加信息。对于 pod 包含节点名。 |
-o yaml |
输出 YAML 格式的 API 对象。 |
kubectl 常用命令(K8S)
指令:https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands
查看k8s下所有资源(pod、service、deploy、副本):kubectl get all 查看k8s下所有资源:
kubectl get all -o wide
查看集群内所有节点:
kubectl get nodes
查看名称空间:
kubectl get ns
service 操作
查看所有 service:
kubectl get svc
查看所有 service 详细信息:
kubectl get svc -o wide
删除 service:
kubectl delete service/tomcat6
查看 kubelet 日志:
journalctl -u kubelet master
容器操作
pod操作
查看所有名称空间的 pod:
kubectl get pods --all-namespaces
查看所有名称空间的 pod 详细信息:
kubectl get pods --all-namespaces -o wide
查看默认名称空间 pods:
kubectl get pods
查看指定名称空间 pod:
kubectl get pods --namespace kube-system
查询 pod 详细信息:
kubectl describe pod tiller-deploy-7b76b656b5-qpmb4 --namespace kube-system
删除 pod:
kubectl delete pod/tomcat6
日志操作
查看日志:
kubectl logs --namespace kubesphere-devops-system
部署操作
使用 yaml 完成部署:
kubectl apply -f tomcat6.yaml
查询部署:
kubectl get deployment
查询名称空间下的部署:
kubectl get deployment -n kube-system
创建一个部署:
kubectl create deployment tomcat6 --image=tomcat:6.0.53-jre8
暴露一个部署。service 随机分配端口:
kubectl expose deployment tomcat6 --port=80 --target-port=8080 --type=NodePort
获取部署的 yaml:
kubectl create deployment tomcat7 --image=tomcat:6.0.53-jre8 --dry-run -o yaml
设置某部署副本数,pod 数:
kubectl scale --replicas=3 deployment tomcat6
删除名称空间下的部署:
kubectl delete deployment tiller-deploy --namespace kube-system
(要删除部署,不要删除 pod,否则会自动部署 pod)
删除部署:
kubectl delete deployment.apps/tomcat6
获取help信息(可以看到 --dry-run -o yaml 生成模板的提示):
kubectl create deployment tomcat6 --image=tomcat:6.0.53-jre8 --help
生成模板到文件 tomcat6.yaml(可以看到--dry-run -o yaml生成模板的提示):
kubectl create deployment tomcat6 --image=tomcat:6.0.53-jre8 --dry-run -o yaml > tomcat6.yaml
应用升级:
kubectl set image
异常解决:
master执行watch kubectl get pod -n kube-system -o wide发现问题
- 找到出问题的主机执行kubectl get pod获取pod的状态
- 查看pod的详细信息:kubectl describe pod elkhost-944bcbcd4-8n9nj
- 查看此pod日志:kubectl logs elkhost-944bcbcd4-8n9nj
kubectl 命令(K8S)
kubectl get
获取列出一个或多个资源的信息。
可以使用的资源包括:
- all
- certificatesigningrequests (aka 'csr')
- clusterrolebindings
- clusterroles
- clusters (valid only for federation apiservers)
- componentstatuses (aka 'cs')
- configmaps (aka 'cm')
- controllerrevisions
- cronjobs
- 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
- storageclasses
- thirdpartyresources
语法
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 信息。
kubectl get pods
列出 Pod 以及运行 Pod 节点信息。
kubectl get pods -o wide
列出指定 NAME 的 replication controller 信息。
kubectl get replicationcontroller web
以 JSON 格式输出一个 pod 信息。
kubectl get -o json pod web-pod-13je7
以“pod.yaml”配置文件中指定资源对象和名称输出 JSON 格式的 Pod 信息。
kubectl get -f pod.yaml -o json
返回指定 pod 的相位值。
kubectl get -o template pod/web-pod-13je7 --template={{.status.phase}}
列出所有 replication controllers 和 service 信息。
kubectl get rc,services
按其资源和名称列出相应信息。
kubectl get rc/web service/frontend pods/web-pod-13je7
列出所有不同的资源对象。
kubectl get all
Flags
Name | Shorthand | Default | Usage |
---|---|---|---|
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. | |
experimental-use-openapi-print-columns | false | If true, use x-kubernetes-print-column metadata (if present) from openapi schema for displaying a resource. | |
export | false | If true, use 'export' for the resources. Exported resources are stripped of cluster-specific information. | |
filename | f | [] | Filename, directory, or URL to files identifying the resource to get from a server. |
ignore-not-found | false | Treat "resource not found" as a successful retrieval. | |
include-extended-apis | true | If true, include definitions of new APIs via calls to the API server. [default true] | |
label-columns | L | [] | 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). | |
output | o | 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]. | |
output-version | DEPRECATED: To use a specific API version, fully-qualify the resource, version, and group (for example: 'jobs.v1.batch/myjob'). | ||
raw | Raw URI to request from the server. Uses the transport specified by the kubeconfig file. | ||
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
schema-cache-dir | ~/.kube/schema | If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema' | |
selector | l | Selector (label query) to filter on, supports '=', '==', and '!='. | |
show-all | a | 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]. | ||
watch | w | false | After listing/getting the requested object, watch for changes. |
watch-only | false | Watch for changes to the requested object(s), without listing/getting first. |
kubectl delete
kubectl delete
通过配置文件名、stdin、资源名称或label选择器来删除资源。
支持 JSON 和 YAML 格式文件。可以只指定一种类型的参数:文件名、资源名称或 label 选择器。
有些资源,如 pod,支持优雅的(graceful)删除,因为这些资源一般是集群中的实体,所以删除不可能会立即生效,这些资源在强制终止之前默认定义了一个周期(宽限期),但是你可以使用 --grace-period flag 来覆盖该值,或者通过 pass --now 设置该周期为 1。
如果托管 Pod 的 Node 节点已经停止或者无法连接 API Server,使用 delete 命令删除 Pod 需等待时间更长。要强制删除资源,需指定 - force flag,且设置周期(宽限期)为 0。
如果执行强制删除 Pod,则调度程序会在节点释放这些 Pod 之前将新的 Pod 放在这些节点上,并使之前 Pod 立即被逐出。
注意:执行 delete 命令时不会检查资源版本,如果在执行 delete 操作时有人进行了更新操作,那么更新操作将连同资源一起被删除。
语法
delete ([-f FILENAME] | TYPE [(NAME | -l label | --all)])
示例
使用 pod.json 中指定的资源类型和名称删除 pod。
kubectl delete -f ./pod.json
根据传入 stdin 的 JSON 所指定的类型和名称删除 pod。
cat pod.json | kubectl delete -f -
删除名为“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
Flags
Name | Shorthand | Default | Usage |
---|---|---|---|
all | false | select all resources in the namespace of the specified resource types. | |
cascade | true | If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). Default true. | |
filename | f | [] | Filename, directory, or URL to files containing the resource to delete. |
force | false | Immediate deletion of some resources may result in inconsistency or data loss and requires confirmation. | |
grace-period | -1 | Period of time in seconds given to the resource to terminate gracefully. Ignored if negative. | |
ignore-not-found | false | Treat "resource not found" as a successful delete. Defaults to "true" when --all is specified. | |
include-extended-apis | true | If true, include definitions of new APIs via calls to the API server. [default true] | |
now | false | If true, resources are signaled for immediate shutdown (same as --grace-period=1). | |
output | o | Output mode. Use "-o name" for shorter output (resource/name). | |
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
selector | l | Selector (label query) to filter on. | |
timeout | 0s | The length of time to wait before giving up on a delete, zero means determine a timeout from the size of the object |
kubectl replace
kubectl replace
使用配置文件或 stdin 来替换资源。
支持 JSON 和 YAML 格式。如果替换当前资源,则必须提供完整的资源规范。可以通过以下命令获取:
kubectl get TYPE NAME -o yaml
请参考https://htmlpreview.github.io/?https://github.com/kubernetes/kubernetes/blob/HEAD/docs/api-reference/v1/definitions.html中的模型,查找字段是否为可变的。
语法
replace -f FILENAME
示例
使用 pod.json 中的数据替换 pod。
kubectl replace -f ./pod.json
根据传入的 JSON 替换 pod。
cat pod.json | kubectl replace -f -
更新镜像版本(tag)到 v4
kubectl get pod mypod -o yaml | sed 's/\(image: myimage\):.*$/\1:v4/' | kubectl replace -f -
强制替换,删除原有资源,然后重新创建资源
kubectl replace --force -f ./pod.json
Flags
Name | Shorthand | Default | Usage |
---|---|---|---|
cascade | false | Only relevant during a force replace. If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a ReplicationController). | |
filename | f | [] | Filename, directory, or URL to files to use to replace the resource. |
force | false | Delete and re-create the specified resource | |
grace-period | -1 | Only relevant during a force replace. Period of time in seconds given to the old resource to terminate gracefully. Ignored if negative. | |
include-extended-apis | true | If true, include definitions of new APIs via calls to the API server. [default true] | |
output | o | Output mode. Use "-o name" for shorter output (resource/name). | |
record | false | Record current kubectl command in the resource annotation. If set to false, do not record the command. If set to true, record the command. If not set, default to updating the existing annotation value only if one already exists. | |
recursive | R | false | Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory. |
save-config | false | If true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future. | |
schema-cache-dir | ~/.kube/schema | If non-empty, load/store cached API schemas in this directory, default is '$HOME/.kube/schema' | |
timeout | 0s | Only relevant during a force replace. The length of time to wait before giving up on a delete of the old resource, zero means determine a timeout from the size of the object. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h). | |
validate | true | If true, use a schema to validate the input before sending it |