kubectl get po,ns

在这里插入图片描述
查看资源的更多信息

kubectl get po -n lady-killer9 -o wide

在这里插入图片描述
可以看到ip等信息

edit

使用默认编辑器编辑资源,默认是yaml

kubectl edit (RESOURCE/NAME | -f FILENAME) [options]

Options:
      --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.
  -f, --filename=[]: Filename, directory, or URL to files to use to edit the resource
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
 -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --output-patch=false: Output the patch if the resource is edited.
      --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.
  -R, --recursive=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.
      --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].
      --validate=true: If true, use a schema to validate the input before sending it
      --windows-line-endings=false: Defaults to the line ending native to your platform.

命令

 kubectl edit ns lady-killer9

结果
在这里插入图片描述
可以看到,在tmp目录下有该文件。这里就不做改变了,个人使用replace多一点。

delete

通过文件、资源名、标签等删除资源,命令格式如下:

  kubectl delete ([-f FILENAME] | [-k DIRECTORY] | TYPE [(NAME | -l label | --all)]) [options]

选项如下:

Options:
      --all=false: Delete all resources, including uninitialized ones, in the namespace of the specified resource types.
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
      --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=[]: containing the resource to delete.
      --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful
deletion. Note that 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.
Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
      --ignore-not-found=false: Treat "resource not found" as a successful delete. Defaults to "true" when --all is
specified.
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
      --now=false: If true, resources are signaled for immediate shutdown (same as --grace-period=1).
  -o, --output='': Output mode. Use "-o name" for shorter output (resource/name).
      --raw='': Raw URI to DELETE to 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, not including uninitialized ones.
      --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
      --wait=true: If true, wait for resources to be gone before returning. This waits for finalizers.

常用选项:

  • – all:删除所有资源,包括未初始化的
  • –now:立刻删除,与–grace-period=1一样
  • –force:立即删除,跳过 grace period,此时设置–grace-period=0
  • –grace-period:优雅删除时间,单位s。
  • -l :标签过滤

因为资源通常代表集群中的实体,所以可能不能够立即删除。例如,删除pod时,确保你的pod已经停止,或强制删除对应用没有影响。
在这里插入图片描述
这是default命名空间的,不是上面自己创建的pod,没有彻底删除,是因为使用的deployment。

集群管理

cluster-info

查看集群信息

 kubectl cluster-info

在这里插入图片描述

top

查看pod或node的资源占用情况

kubectl top pod/node

在这里插入图片描述

cordon && uncordon

节点是否可以调度,命令格式:

kubectl cordon/uncordon NODE [options]

选项如下:

Options:
      --dry-run=false: If true, only print the object that would be sent, without sending it.
  -l, --selector='': Selector (label query) to filter on

在资源调度的文章中再展示

drain

驱逐节点,为维护做好准备。
节点将标记为不可调度,使用uncordon使节点可以调度,命令格式:

kubectl drain NODE [options]

选项如下:

Options:
      --delete-local-data=false: Continue even if there are pods using emptyDir (local data that will be deleted when
the node is drained).
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --force=false: Continue even if there are pods not managed by a ReplicationController, ReplicaSet, Job, DaemonSet or StatefulSet.
      --grace-period=-1: Period of time in seconds given to each pod to terminate gracefully. If negative, the default value specified in the pod will be used.
      --ignore-daemonsets=false: Ignore DaemonSet-managed pods.
      --pod-selector='': Label selector to filter pods on the node
  -l, --selector='': Selector (label query) to filter on
      --timeout=0s: The length of time to wait before giving up, zero means infinite

  • –ignore-daemonsets:有守护进程的POD也会删除
  • –force:继续即使有不被 RC RS Job DS STS管理的Pod

例如

kubectl drain foo --force

taint

更新节点上的污点。

  • 污点由 key, value 和effect组成,例如,key=value:effect。
  • key必须以字母或数字开头,可以包含字母、数字、连字符、点和下划线,最多253个字符。
  • value是可选的,如果给定,必须以字母或数字开头,可以包含字母、数字、连字符、点和下划线,最多63个字符。
  • effect必须是NoSchedule、PreferNoSchedule或NoExecute。

命令格式如下:

kubectl taint NODE NAME KEY\_1=VAL_1:TAINT_EFFECT_1 ... KEY\_N=VAL_N:TAINT_EFFECT_N [options]

选项如下:

Options:
      --all=false: Select all nodes in the cluster
      --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.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --overwrite=false: If true, allow taints to be overwritten, otherwise reject taint updates that overwrite existing taints.
  -l, --selector='': Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)
      --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].
      --validate=true: If true, use a schema to validate the input before sending it

  • –all:全部节点
  • –overwrite:如果为true,则允许覆盖污点,否则拒绝覆盖现有的污点。
  • -l:筛选

添加污点

kubectl taint nodes foo dedicated=special-user:NoSchedule

移除污点

kubectl taint nodes foo dedicated:NoSchedule-

根据label添加污点

  kubectl taint node -l myLabel=X  dedicated=foo:PreferNoSchedule

在资源调度的文章中再展示

高级命令

apply

将配置应用于某资源,若资源还不存在就创建。和create --save-config差不多。命令格式如下:

  kubectl apply (-f FILENAME | -k DIRECTORY) [options]

选项如下:

Options:
      --all=false: Select all resources in the namespace of the specified resource types.
      --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.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
      --dry-run=false: If true, only print the object that would be sent, without sending it. Warning: --dry-run cannot
accurately output the result of merging the local manifest and the server-side data. Use --server-dry-run to get the
merged result instead.
      --field-manager='kubectl': Name of the manager used to track field ownership.
  -f, --filename=[]: that contains the configuration to apply
      --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful
deletion. Note that immediate deletion of some resources may result in inconsistency or data loss and requires
confirmation.
      --force-conflicts=false: If true, server-side apply will force the changes against conflicts.
      --grace-period=-1: Period of time in seconds given to the resource to terminate gracefully. Ignored if negative.
Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
      --openapi-patch=true: If true, use openapi to calculate diff when the openapi presents and the resource can be
found in the openapi spec. Otherwise, fall back to use baked-in types.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --overwrite=true: Automatically resolve conflicts between the modified and live configuration by using values from
the modified configuration
      --prune=false: Automatically delete resource objects, including the uninitialized ones, that do not appear in the
configs and are created by either apply or create --save-config. Should be used with either -l or --all.
      --prune-whitelist=[]: Overwrite the default whitelist with <group/version/kind> for --prune
      --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.
  -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)
      --server-dry-run=false: If true, request will be sent to server with dry-run flag, which means the modifications
won't be persisted. This is an alpha feature and flag.
      --server-side=false: If true, apply runs in the server instead of the client.
      --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].
      --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
      --validate=true: If true, use a schema to validate the input before sending it
      --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.

例子,
nginx-test-apply.yaml

apiVersion: v1
kind: Pod
metadata:
  name: nginx-test-apply
  labels:
    app: nginx
    role: backend
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - name: http
      containerPort: 80


命令

kubectl apply -f nginx-test-apply.yaml -n lady-killer9

结果
在这里插入图片描述
相对于create,文件没有改动时不会报错。

replace

替换资源,命令格式如下:

kubectl replace -f FILENAME [options]

选项如下:

Options:
      --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.
      --cascade=true: If true, cascade the deletion of the resources managed by this resource (e.g. Pods created by a
ReplicationController).  Default true.
  -f, --filename=[]: to use to replace the resource.
      --force=false: Only used when grace-period=0. If true, immediately remove resources from API and bypass graceful
deletion. Note that 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.
Set to 1 for immediate shutdown. Can only be set to 0 when --force is true (force deletion).
  -k, --kustomize='': Process a kustomization directory. This flag can't be used together with -f or -R.
 -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --raw='': Raw URI to PUT to 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.
      --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.
      --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].
      --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
      --validate=true: If true, use a schema to validate the input before sending it
      --wait=false: If true, wait for resources to be gone before returning. This waits for finalizers.


只能替换部分字段,尝试修改spec.containers的ports字段

apiVersion: v1
kind: Pod
metadata:
  name: nginx-test-apply
  labels:
    app: nginx
    role: backend
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - name: http
      containerPort: 80
    - name: https
      containerPort: 443

命令

kubectl replace -f nginx-test-apply.yaml -n lady-killer9ls

结果
在这里插入图片描述
pod更新不能更改spec.containers[*].image, spec.initContainers[*].image, spec.activeDeadlineSeconds 或者spec.tolerations (仅添加到现有的toleration中)以外的字段

故障诊断和调试

describe

显示指定资源或资源组的详细信息,命令格式如下:

 kubectl describe (-f FILENAME | TYPE [NAME_PREFIX | -l label] | TYPE/NAME) [options]

选项如下:

Options:
  -A, --all-namespaces=false: If present, list the requested object(s) across all namespaces. Namespace in current
context is ignored even if specified with --namespace.
  -f, --filename=[]: Filename, directory, or URL to files containing the resource to describe
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
  -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)
      --show-events=true: If true, display events related to the described object.

例子,
命令

  kubectl describe po/nginx-test-apply -n lady-killer9

结果
在这里插入图片描述

logs

打印pod或指定资源中容器的日志。如果pod只有一个容器,则容器名称是可选的。命令格式如下:

kubectl logs [-f] [-p] (POD | TYPE/NAME) [-c CONTAINER] [options]

选项如下:

Options:
      --all-containers=false: Get all containers' logs in the pod(s).
 -c, --container='': Print the logs of this container
  -f, --follow=false: Specify if the logs should be streamed.
      --ignore-errors=false: If watching / following pod logs, allow for any errors that occur to be non-fatal
      --insecure-skip-tls-verify-backend=false: Skip verifying the identity of the kubelet that logs are requested from.
In theory, an attacker could provide invalid log content back. You might want to use this if your kubelet serving
certificates have expired.
      --limit-bytes=0: Maximum bytes of logs to return. Defaults to no limit.
      --max-log-requests=5: Specify maximum number of concurrent logs to follow when using by a selector. Defaults to 5.
      --pod-running-timeout=20s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
      --prefix=false: Prefix each log line with the log source (pod name and container name)
  -p, --previous=false: If true, print the logs for the previous instance of the container in a pod if it exists.
  -l, --selector='': Selector (label query) to filter on.
      --since=0s: Only return logs newer than a relative duration like 5s, 2m, or 3h. Defaults to all logs. Only one of
since-time / since may be used.
      --since-time='': Only return logs after a specific date (RFC3339). Defaults to all logs. Only one of since-time /
since may be used.
      --tail=-1: Lines of recent log file to display. Defaults to -1 with no selector, showing all log lines otherwise
10, if a selector is provided.
      --timestamps=false: Include timestamps on each line in the log output

  • –all-containers:pod中所有容器的日志
  • -p:如果为true,则打印pod中容器的前一个实例(如果存在)的日志。
  • -c:指定容器
  • –tail:看最近的日志
  • –since: 看最近多久时间的日志

例子:
查看pod nginx-test-apply日志

kubectl logs po/nginx-test-apply -n lady-killer9

在这里插入图片描述
查看pod nginx-test-apply中 nginx容器的日志

kubectl logs po/nginx-test-apply -c nginx -n lady-killer9

结果同上
查看pod nginx-test-apply后10行日志

kubectl logs --tail=10 po/nginx-test-apply

在这里插入图片描述
查看pod nginx-test-apply近一个小时的日志

kubectl logs --since=1h po/nginx-test-apply -n lady-killer9

在这里插入图片描述

exec

在容器中执行命令。未指定pod中的容器时默认为第一个。命令格式如下:

kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...] [options]

选项如下:

Options:
  -c, --container='': Container name. If omitted, the first container in the pod will be chosen
      --pod-running-timeout=1m0s: The length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one
pod is running
  -i, --stdin=false: Pass stdin to the container
  -t, --tty=false: Stdin is a TTY

例子,
在pod nginx-test-apply的第一个容器中指定date命令

kubectl exec nginx-test-apply -n lady-killer9 date

结果
在这里插入图片描述
把输入定向到容器中,结果返回出来,形成类似反弹shell的交互式命令

kubectl exec nginx-test-apply -n lady-killer9 -i -t -- bash -il

在这里插入图片描述
执行的命令有参数,使用 –

kubectl exec nginx-test-apply -n lady-killer9 -i -t -- ls -t /usr/local/

结果
在这里插入图片描述

设置命令

label

添加、更新、删除资源上的标签。

  • 标签的key和value必须以字母或数字开头,可以包含字母、数字、连字符、点和数字
    下划线,每个下划线最多63个字符。
  • 如果–overwrite为true,则可以覆盖现有标签,否则尝试覆盖标签将失败导致错误。
  • 如果指定了–resource version,则更新将使用此资源版本,否则现有的将使用资源版本。

命令格式如下:

kubectl label [--overwrite] (-f FILENAME | TYPE NAME) KEY\_1=VAL_1 ... KEY\_N=VAL_N [--resource-version=version][options]

选项如下:

Options:
      --all=false: Select all resources, including uninitialized ones, in the namespace of the specified resource types
      --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.
      --dry-run=false: If true, only print the object that would be sent, without sending it.
      --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 update the labels
  -k, --kustomize='': Process the kustomization directory. This flag can't be used together with -f or -R.
      --list=false: If true, display the labels for a given resource.
      --local=false: If true, label will NOT contact api-server but run locally.
  -o, --output='': Output format. One of:
json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-file.
      --overwrite=false: If true, allow labels to be overwritten, otherwise reject label updates that overwrite existing
labels.
      --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.
  -R, --recursive=false: Process the directory used in -f, --filename recursively. Useful when you want to manage
related manifests organized within the same directory.
      --resource-version='': If non-empty, the labels update will only succeed if this is the current resource-version
for the object. Only valid when specifying a single resource.
  -l, --selector='': Selector (label query) to filter on, not including uninitialized ones, supports '=', '==', and
'!='.(e.g. -l key1=value1,key2=value2).
      --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].

添加

kubectl label node k8s-node01 unhealthy=true

在这里插入图片描述
查看

kubectl get node --show-labels

在这里插入图片描述

更新

kubectl label --overwrite node k8s-node01 unhealthy=false

在这里插入图片描述
删除

kubectl label  node k8s-node01 unhealthy-

在这里插入图片描述

其他命令

version

学习路线:

这个方向初期比较容易入门一些,掌握一些基本技术,拿起各种现成的工具就可以开黑了。不过,要想从脚本小子变成黑客大神,这个方向越往后,需要学习和掌握的东西就会越来越多以下是网络渗透需要学习的内容:
在这里插入图片描述

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以点击这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐