其他分享
首页 > 其他分享> > 超11万字整理完k8s的核心组件pod全部功能详解,理论代码超详细,建议跟着做一遍实验【含 label 标签使用】【1】

超11万字整理完k8s的核心组件pod全部功能详解,理论代码超详细,建议跟着做一遍实验【含 label 标签使用】【1】

作者:互联网

文章目录

说明【必看】

在这里插入图片描述

第二篇文章标题和链接

第二篇文章标题和链接

文章链接:

标题如下:
在这里插入图片描述
在这里插入图片描述

第三篇文章标题和链接

文章链接:

标题如下:
在这里插入图片描述
在这里插入图片描述

创建及删除pod

创建一个pod-1的文件夹和命名空间

[root@master wal]# mkdir pod-1
[root@master wal]# cd pod-1
[root@master pod-1]# 
[root@master pod-1]# kubectl create ns pod-1
namespace/pod-1 created
[root@master pod-1]# # 下面命令是切换到pod-1这个命名空间,kubens命令是需要单独安装的。
[root@master pod-1]# kubens pod-1
Context "context" modified.
Active namespace is "pod-1".
[root@master pod-1]# 
[root@master pod-1]# kubectl config get-contexts 
CURRENT   NAME           CLUSTER   AUTHINFO   NAMESPACE
*         context        master    ccx        pod-1
          context1-new   master1   ccx1       default
[root@master pod-1]# 

k8s安装metric server和了解namespace【命名空间】,含k8s pod状态为ImagePullBackOff处理方法

镜像准备【node节点执行】

[root@master pod-1]# kubectl get nodes
NAME     STATUS   ROLES    AGE    VERSION
master   Ready    <none>   3d6h   v1.21.0
node1    Ready    <none>   3d6h   v1.21.0
node2    Ready    <none>   3d6h   v1.21.0
[root@master pod-1]# 
[root@node1 ~]# docker images | grep nginx
nginx                                                             latest     d1a364dc548d   7 weeks ago     133MB
[root@node1 ~]# 

[root@node2 ~]# docker images | grep nginx
nginx                                                             latest     d1a364dc548d   7 weeks ago     133MB
[root@node2 ~]#

创建pod【虚拟机】

方式1:命令行的方式【不建议】

默认创建

在这里插入图片描述

[root@master pod-1]# kubectl run pod1 --image=nginx
pod/pod1 created
[root@master pod-1]# 
[root@master pod-1]# kubectl get pods 
NAME   READY   STATUS             RESTARTS   AGE
pod1   0/1     ImagePullBackOff   0          7s
[root@master pod-1]# kubectl describe pod pod1 #这是日志查看报错信息

加imagePullPolicy参数创建

[root@master ~]# docker images | grep nginx
#当前是master节点,这上面没有nginx镜像, 但是我node节点上有nginx镜像!!!!
[root@master ~]#
[root@master ~]# kubectl get pods
No resources found in pod-1 namespace.
[root@master ~]# kubectl run pod1 --image=nginx --image-pull-policy=IfNotPresent
pod/pod1 created
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          17s
[root@master ~]# 
[root@master ~]# ping -w 2 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.

--- 8.8.8.8 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 1999ms

[root@master ~]# 

说明

[root@master ~]# kubectl run pod1 --image=nginx --image-pull-policy=IfNotPresent --env "aa=bb" --env "cc=dd" --labels="aa=bb,cc=dd"
pod/pod1 created
[root@master ~]# 
[root@master ~]# kubectl exec -it pod1 -- bash
root@pod1:/# echo $aa
bb
root@pod1:/# echo $bb

root@pod1:/# echo $cc
dd
root@pod1:/# 
root@pod1:/# exit
exit
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          43s
[root@master ~]# kubectl get pods --show-labels 
NAME   READY   STATUS    RESTARTS   AGE   LABELS
pod1   1/1     Running   0          55s   aa=bb,cc=dd
[root@master ~]# 
[root@master ~]# 

方式2:yaml文件的方式创建【建议】

这种方式还有一个最大的好处就是,可以用同一个配置文件创建多个pod【下面会说明的】

获取yaml文件

kubectl run 自定义pod名称 --image=镜像名称 --image-pull-policy=下载策略 --dry-run=client/server -o yaml > 自定义名称.yaml

#--image-pull-policy=有3种策略,加上面命令行中加参数创建

# --dry-run=这是模拟运行的意思
#--dry-run=client:简洁输出【一般用这个比较多】
#--dry-run=server:详细输出,内容很多

# -o yaml :以yaml文件的形式输出

# > 自定义名称.yaml :如果不加这个,就直接打印到屏幕上
[root@master ~]# kubectl delete pod pod1
pod "pod1" deleted
[root@master ~]# 
[root@master ~]# kubectl run pod1 --image=nginx --image-pull-policy=IfNotPresent --dry-run=client -o yaml > pod1.yaml
[root@master ~]# 
[root@master ~]# kubectl get pods
No resources found in pod-1 namespace.
[root@master ~]# 

获取的配置文件说明

[root@master ~]# vim pod1.yaml 
apiVersion: v1 
kind: Pod 
metadata: 
  creationTimestamp: null 
  labels: 
    run: pod1 
  name: pod1 
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: pod1
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
yaml文件格式说明
一级参数获取
[root@master ~]# kubectl explain pods
KIND:     Pod
VERSION:  v1

DESCRIPTION:
     Pod is a collection of containers that can run on a host. This resource is
     created by clients and scheduled onto hosts.

FIELDS:
   apiVersion   <string>
     APIVersion defines the versioned schema of this representation of an
     object. Servers should convert recognized schemas to the latest internal
     value, and may reject unrecognized values. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources

   kind <string>
     Kind is a string value representing the REST resource this object
     represents. Servers may infer this from the endpoint the client submits
     requests to. Cannot be updated. In CamelCase. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds

   metadata     <Object>
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   spec <Object>
     Specification of the desired behavior of the pod. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

   status       <Object>
     Most recently observed status of the pod. This data may not be up to date.
     Populated by the system. Read-only. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status

[root@master ~]# 
二级菜单获取
[root@master ~]# kubectl explain pods.metadata
KIND:     Pod
VERSION:  v1

RESOURCE: metadata <Object>

DESCRIPTION:
     Standard object's metadata. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

     ObjectMeta is metadata that all persisted resources must have, which
     includes all objects users must create.

FIELDS:
   annotations  <map[string]string>
     Annotations is an unstructured key value map stored with a resource that
     may be set by external tools to store and retrieve arbitrary metadata. They
     are not queryable and should be preserved when modifying objects. More
     info: http://kubernetes.io/docs/user-guide/annotations

   clusterName  <string>
     The name of the cluster which the object belongs to. This is used to
     distinguish resources with same name and namespace in different clusters.
     This field is not set anywhere right now and apiserver is going to ignore
     it if set in create or update request.

   creationTimestamp    <string>
     CreationTimestamp is a timestamp representing the server time when this
     object was created. It is not guaranteed to be set in happens-before order
     across separate operations. Clients may not set this value. It is
     represented in RFC3339 form and is in UTC.

     Populated by the system. Read-only. Null for lists. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   deletionGracePeriodSeconds   <integer>
     Number of seconds allowed for this object to gracefully terminate before it
     will be removed from the system. Only set when deletionTimestamp is also
     set. May only be shortened. Read-only.

   deletionTimestamp    <string>
     DeletionTimestamp is RFC 3339 date and time at which this resource will be
     deleted. This field is set by the server when a graceful deletion is
     requested by the user, and is not directly settable by a client. The
     resource is expected to be deleted (no longer visible from resource lists,
     and not reachable by name) after the time in this field, once the
     finalizers list is empty. As long as the finalizers list contains items,
     deletion is blocked. Once the deletionTimestamp is set, this value may not
     be unset or be set further into the future, although it may be shortened or
     the resource may be deleted prior to this time. For example, a user may
     request that a pod is deleted in 30 seconds. The Kubelet will react by
     sending a graceful termination signal to the containers in the pod. After
     that 30 seconds, the Kubelet will send a hard termination signal (SIGKILL)
     to the container and after cleanup, remove the pod from the API. In the
     presence of network partitions, this object may still exist after this
     timestamp, until an administrator or automated process can determine the
     resource is fully terminated. If not set, graceful deletion of the object
     has not been requested.

     Populated by the system when a graceful deletion is requested. Read-only.
     More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

   finalizers   <[]string>
     Must be empty before the object is deleted from the registry. Each entry is
     an identifier for the responsible component that will remove the entry from
     the list. If the deletionTimestamp of the object is non-nil, entries in
     this list can only be removed. Finalizers may be processed and removed in
     any order. Order is NOT enforced because it introduces significant risk of
     stuck finalizers. finalizers is a shared field, any actor with permission
     can reorder it. If the finalizer list is processed in order, then this can
     lead to a situation in which the component responsible for the first
     finalizer in the list is waiting for a signal (field value, external
     system, or other) produced by a component responsible for a finalizer later
     in the list, resulting in a deadlock. Without enforced ordering finalizers
     are free to order amongst themselves and are not vulnerable to ordering
     changes in the list.

   generateName <string>
     GenerateName is an optional prefix, used by the server, to generate a
     unique name ONLY IF the Name field has not been provided. If this field is
     used, the name returned to the client will be different than the name
     passed. This value will also be combined with a unique suffix. The provided
     value has the same validation rules as the Name field, and may be truncated
     by the length of the suffix required to make the value unique on the
     server.

     If this field is specified and the generated name exists, the server will
     NOT return a 409 - instead, it will either return 201 Created or 500 with
     Reason ServerTimeout indicating a unique name could not be found in the
     time allotted, and the client should retry (optionally after the time
     indicated in the Retry-After header).

     Applied only if Name is not specified. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#idempotency

   generation   <integer>
     A sequence number representing a specific generation of the desired state.
     Populated by the system. Read-only.

   labels       <map[string]string>
     Map of string keys and values that can be used to organize and categorize
     (scope and select) objects. May match selectors of replication controllers
     and services. More info: http://kubernetes.io/docs/user-guide/labels

   managedFields        <[]Object>
     ManagedFields maps workflow-id and version to the set of fields that are
     managed by that workflow. This is mostly for internal housekeeping, and
     users typically shouldn't need to set or understand this field. A workflow
     can be the user's name, a controller's name, or the name of a specific
     apply path like "ci-cd". The set of fields is always in the version that
     the workflow used when modifying the object.

   name <string>
     Name must be unique within a namespace. Is required when creating
     resources, although some resources may allow a client to request the
     generation of an appropriate name automatically. Name is primarily intended
     for creation idempotence and configuration definition. Cannot be updated.
     More info: http://kubernetes.io/docs/user-guide/identifiers#names

   namespace    <string>
     Namespace defines the space within which each name must be unique. An empty
     namespace is equivalent to the "default" namespace, but "default" is the
     canonical representation. Not all objects are required to be scoped to a
     namespace - the value of this field for those objects will be empty.

     Must be a DNS_LABEL. Cannot be updated. More info:
     http://kubernetes.io/docs/user-guide/namespaces

   ownerReferences      <[]Object>
     List of objects depended by this object. If ALL objects in the list have
     been deleted, this object will be garbage collected. If this object is
     managed by a controller, then an entry in this list will point to this
     controller, with the controller field set to true. There cannot be more
     than one managing controller.

   resourceVersion      <string>
     An opaque value that represents the internal version of this object that
     can be used by clients to determine when objects have changed. May be used
     for optimistic concurrency, change detection, and the watch operation on a
     resource or set of resources. Clients must treat these values as opaque and
     passed unmodified back to the server. They may only be valid for a
     particular resource or set of resources.

     Populated by the system. Read-only. Value must be treated as opaque by
     clients and . More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency

   selfLink     <string>
     SelfLink is a URL representing this object. Populated by the system.
     Read-only.

     DEPRECATED Kubernetes will stop propagating this field in 1.20 release and
     the field is planned to be removed in 1.21 release.

   uid  <string>
     UID is the unique in time and space value for this object. It is typically
     generated by the server on successful creation of a resource and is not
     allowed to change on PUT operations.

     Populated by the system. Read-only. More info:
     http://kubernetes.io/docs/user-guide/identifiers#uids

[root@master ~]# 
三级菜单获取
[root@master ~]# kubectl explain pods.metadata.creationTimestamp
KIND:     Pod
VERSION:  v1

FIELD:    creationTimestamp <string>

DESCRIPTION:
     CreationTimestamp is a timestamp representing the server time when this
     object was created. It is not guaranteed to be set in happens-before order
     across separate operations. Clients may not set this value. It is
     represented in RFC3339 form and is in UTC.

     Populated by the system. Read-only. Null for lists. More info:
     https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata

     Time is a wrapper around time.Time which supports correct marshaling to
     YAML and JSON. Wrappers are provided for many of the factory methods that
     the time package offers.
[root@master ~]# 
[root@master ~]# 
[root@master ~]# 
[root@master ~]# kubectl explain pods.metadata.labels
KIND:     Pod
VERSION:  v1

FIELD:    labels <map[string]string>

DESCRIPTION:
     Map of string keys and values that can be used to organize and categorize
     (scope and select) objects. May match selectors of replication controllers
     and services. More info: http://kubernetes.io/docs/user-guide/labels
[root@master ~]# 

配置文件中“-”的作用以及啥时候需要加“-”

说明

在这里插入图片描述
如果还不能理解,没关系,我下面用一个demo再说明

demo说明
spec: #字典
  containers:#字典
  - image: nginx #列表
    imagePullPolicy: IfNotPresent#列表内容
    name: pod1#列表内容
    resources: {}#列表内容
  dnsPolicy: ClusterFirst#字典
spec: #字典
  containers:#字典
  - image: nginx #列表
    imagePullPolicy: IfNotPresent#列表内容
    name: pod1#列表内容
    resources: {}#列表内容
    ...#可以新增自定义列表内容的
  - image: nginx #列表
    imagePullPolicy: IfNotPresent#列表内容
    name: pod1#列表内容
    resources: {}#列表内容
    ...#可以新增自定义列表内容的
  - image: nginx #列表
    imagePullPolicy: IfNotPresent#列表内容
    name: pod1#列表内容
    resources: {}#列表内容    
    ...#可以新增自定义列表内容的  
  dnsPolicy: ClusterFirst#字典

restartPolicy 参数说明

  restartPolicy: Always
[root@master ~]# kubectl explain pods.spec.restartPolicy
KIND:     Pod
VERSION:  v1

FIELD:    restartPolicy <string>

DESCRIPTION:
     Restart policy for all containers within the pod. One of Always, OnFailure,
     Never. Default to Always. More info:
     https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy
[root@master ~]# 

编辑配置文件

[root@master ~]# cat pod1.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod1
  name: pod1
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: pod1
    resources: {}
    env:
    - name: aa
      value: xxx
    - name: bb
      value: "888"
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
[root@master ~]#

通过文件创建pod

[root@master ~]# kubectl apply -f pod1.yaml
pod/pod1 created
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          32s
[root@master ~]# 

通过文件创建多个pod

[root@master ~]# cat pod1.yaml 
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod1
  name: pod1
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: pod1
    resources: {}
    env:
    - name: aa
      value: xxx
    - name: bb
      value: "888"
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
[root@master ~]# 
sed 's/pod1/pod2/' pod1.yaml | kubectl apply -f -

#pod1:是配置文件中的name
#pod2:是新名【自定义】 【如果要创建更多,仅修改这个值】
# pod1.yaml是配置文件名称
[root@master ~]# kubectl get pods
No resources found in pod-1 namespace.
[root@master ~]# 
[root@master ~]# kubectl apply -f pod1.yaml 
pod/pod1 created
[root@master ~]# sed 's/pod1/pod2/' pod1.yaml  | kubectl apply -f -
pod/pod2 created
[root@master ~]# 
[root@master ~]# sed 's/pod1/pod3/' pod1.yaml  | kubectl apply -f -
pod/pod3 created
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          35s
pod2   1/1     Running   0          15s
pod3   1/1     Running   0          5s
[root@master ~]# 

创建pod报错…expected "map"处理

[root@master ~]# kubectl apply -f pod1.yaml
error: error validating "pod1.yaml": error validating data: [ValidationError(Pod.spec.containers[0].env[0]): invalid type for io.k8s.api.core.v1.EnvVar: got "string", expected "map", ValidationError(Pod.spec.containers[0].env[1]): invalid type for io.k8s.api.core.v1.EnvVar: got "string", expected "map"]; if you choose to ignore these errors, turn validation off with --validate=false

[root@master ~]# kubectl apply -f pod1.yaml
error: error parsing pod1.yaml: error converting YAML to JSON: yaml: line 17: could not find expected ':'

删除pod

pod名称方式删除【建议】

[root@master pod-1]# kubectl delete pod pod1
pod "pod1" deleted
[root@master pod-1]# 
[root@master pod-1]# kubectl get pods
No resources found in pod-1 namespace.
[root@master pod-1]# 

配置文件方式删除

[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          10m
[root@master ~]# 
[root@master ~]# kubectl delete -f pod1.yaml 
pod "pod1" deleted
[root@master ~]# 
[root@master ~]# kubectl get pods
No resources found in pod-1 namespace.
[root@master ~]# 

pod的几种状态说明

[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          3d6h
pod2   2/2     Running   27         3d5h
[root@master ~]#

一个pod运行多个容器

[root@master ~]# cp pod1.yaml pod2.yaml

并在里面执行一下全局替换,将pod1替换为pod2
在这里插入图片描述

[root@master ~]# cat pod2.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod2
  name: pod2
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: pod2
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
[root@master ~]#

说明

容器的CMD说明

[root@master ~]# cat pod2.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod2
  name: pod2
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c2
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
[root@master ~]# 
[root@master ~]# kubectl apply -f pod2.yaml
pod/pod2 created
[root@master ~]# kubectl get pod
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          31m
pod2   1/2     Error     1          11s
[root@master ~]# 

指定容器CMD并创建

[root@master ~]# vim pod2.yaml 
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod2
  name: pod2
spec:
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  - image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 10"]
    name: c2
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
~
~
~
~
~
"pod2.yaml" 21L, 379C written                                    
[root@master ~]# 
[root@master ~]# kubectl delete pod pod2 --force
warning: Immediate deletion does not wait for confirmation that the running resource has been terminated. The resource may continue to run on the cluster indefinitely.
pod "pod2" force deleted
[root@master ~]# 
[root@master ~]# kubectl apply -f pod2.yaml 
pod/pod2 created
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          35m
pod2   2/2     Running   0          7s
[root@master ~]# 

可以看到增加cmd内容以后,创建的pod 状态就为Running了

[root@master ~]# kubectl get pods
NAME   READY   STATUS             RESTARTS   AGE
pod1   1/1     Running            0          37m
pod2   1/2     CrashLoopBackOff   3          104s
[root@master ~]# kubectl get pods
NAME   READY   STATUS             RESTARTS   AGE
pod1   1/1     Running            0          37m
pod2   1/2     CrashLoopBackOff   3          107s
[root@master ~]# kubectl get pods
NAME   READY   STATUS     RESTARTS   AGE
pod1   1/1     Running    0          37m
pod2   1/2     NotReady   4          2m26s
[root@master ~]# 
[root@master ~]# kubectl get pods
NAME   READY   STATUS     RESTARTS   AGE
pod1   1/1     Running    0          37m
pod2   1/2     NotReady   4          2m31s

在pod里执行一些命令

查看pod详细信息

[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          77m
pod2   2/2     Running   0          5s
[root@master ~]# kubectl describe pod pod2
Name:         pod2
Namespace:    pod-1
Priority:     0
Node:         node1/192.168.59.143
Start Time:   Fri, 23 Jul 2021 12:17:01 +0800
Labels:       run=pod2
Annotations:  cni.projectcalico.org/podIP: 10.244.166.135/32
              cni.projectcalico.org/podIPs: 10.244.166.135/32
Status:       Running
IP:           10.244.166.135
IPs:
  IP:  10.244.166.135
Containers:
  c1:
    Container ID:   docker://32da51b11a075f077c392a8bab1a0aaa34423de21ee6a357d5ea15dadc8fee35
    Image:          nginx
    Image ID:       docker://sha256:d1a364dc548d5357f0da3268c888e1971bbdb957ee3f028fe7194f1d61c6fdee
    Port:           <none>
    Host Port:      <none>
    State:          Running
      Started:      Fri, 23 Jul 2021 12:17:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-x8cql (ro)
  c2:
    Container ID:  docker://fe480106b8205a38e22997f2611382e964f6ab9161cb23df2046ffc5d61cf216
    Image:         nginx
    Image ID:      docker://sha256:d1a364dc548d5357f0da3268c888e1971bbdb957ee3f028fe7194f1d61c6fdee
    Port:          <none>
    Host Port:     <none>
    Command:
      sh
      -c
      sleep 10000
    State:          Running
      Started:      Fri, 23 Jul 2021 12:17:03 +0800
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-x8cql (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-x8cql:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3607
    ConfigMapName:           kube-root-ca.crt
    ConfigMapOptional:       <nil>
    DownwardAPI:             true
QoS Class:                   BestEffort
Node-Selectors:              <none>
Tolerations:                 node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                             node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  12s   default-scheduler  Successfully assigned pod-1/pod2 to node1
  Normal  Pulled     11s   kubelet            Container image "nginx" already present on machine
  Normal  Created    10s   kubelet            Created container c1
  Normal  Started    10s   kubelet            Started container c1
  Normal  Pulled     10s   kubelet            Container image "nginx" already present on machine
  Normal  Created    10s   kubelet            Created container c2
  Normal  Started    10s   kubelet            Started container c2
[root@master ~]# 

不进入bash直接执行pod容器命令

只有一个容器的情况下

[root@master ~]# kubectl exec pod1 -- ls /tmp
[root@master ~]# 
[root@master ~]# kubectl exec pod1 -- ls /root
[root@master ~]# kubectl exec pod1 -- ls /var/log
apt
btmp
dpkg.log
faillog
lastlog
nginx
wtmp



#比如容器中命令不存在,那么就会报如下错误

[root@master ~]# kubectl exec pod1 -- ifconfig
OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: "ifconfig": executable file not found in $PATH: unknown
command terminated with exit code 126
[root@master ~]# 

指定pod容器查看

[root@master ~]# kubectl get pod
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          79m
pod2   2/2     Running   0          2m
[root@master ~]# 
[root@master ~]# kubectl exec pod2 -- ls /tmp
Defaulted container "c1" out of: c1, c2
[root@master ~]# 
[root@master ~]# kubectl exec pod2 -c c1 -- ls /tmp
[root@master ~]# 
[root@master ~]# kubectl exec pod2 -c c2 -- ls /tmp
[root@master ~]# 

创建bash并进入pod容器

只有一个容器的情况下

[root@master ~]# kubectl exec -it pod1 -- bash
root@pod1:/# 
root@pod1:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var
root@pod1:/# pwd
/
root@pod1:/# 

# 这种比较直观,命令不存在的话正常提示,而不是报错
root@pod1:/# ifconfig
bash: ifconfig: command not found
root@pod1:/# 
root@pod1:/# exit
exit
command terminated with exit code 127
[root@master ~]# 

指定pod容器查看

[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          81m
pod2   2/2     Running   0          4m34s
[root@master ~]# 
[root@master ~]# kubectl exec -it pod2 -- bash
Defaulted container "c1" out of: c1, c2
root@pod2:/# 
root@pod2:/# exit
exit
[root@master ~]#
[root@master ~]# kubectl exec -it pod2 -c c1 -- bash
root@pod2:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var
root@pod2:/# exit
exit
[root@master ~]# 
[root@master ~]# kubectl exec -it pod2 -c c2 -- bash
root@pod2:/# ls
bin   docker-entrypoint.d   home   media  proc  sbin  tmp
boot  docker-entrypoint.sh  lib    mnt    root  srv   usr
dev   etc                   lib64  opt    run   sys   var
root@pod2:/# exit
exit
[root@master ~]#

拷贝本地文件到pod容器内【含反过来拷贝】

[root@master ~]# kubectl cp /etc/hosts pod1:/tmp
[root@master ~]# 
[root@master ~]# kubectl exec -it pod1 -- bash
root@pod1:/# ls /tmp/
hosts
root@pod1:/# cat hosts
cat: hosts: No such file or directory
root@pod1:/# cat /tmp/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

192.168.59.142 master
192.168.59.143 node1
192.168.59.144 node2

root@pod1:/# 
[root@master ~]# kubectl cp  pod1:/etc/hosts hosts
tar: Removing leading `/' from member names
[root@master ~]#
[root@master ~]# cat hosts 
# Kubernetes-managed hosts file.
127.0.0.1       localhost
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
fe00::0 ip6-mcastprefix
fe00::1 ip6-allnodes
fe00::2 ip6-allrouters
10.244.104.5    pod1
[root@master ~]# 
[root@master ~]# rm -rf hosts 
[root@master ~]# 

指定pod容器

方法见上面bash的用法吧,方法都一样,就加个参数-c 容器名 罢了

查看pod容器日志输出【用于排错】

[root@master ~]# kubectl logs pod1
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2021/07/23 02:59:49 [notice] 1#1: using the "epoll" event method
2021/07/23 02:59:49 [notice] 1#1: nginx/1.21.0
2021/07/23 02:59:49 [notice] 1#1: built by gcc 8.3.0 (Debian 8.3.0-6) 
2021/07/23 02:59:49 [notice] 1#1: OS: Linux 3.10.0-957.el7.x86_64
2021/07/23 02:59:49 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2021/07/23 02:59:49 [notice] 1#1: start worker processes
2021/07/23 02:59:49 [notice] 1#1: start worker process 31
2021/07/23 02:59:49 [notice] 1#1: start worker process 32
2021/07/23 02:59:49 [notice] 1#1: start worker process 33
2021/07/23 02:59:49 [notice] 1#1: start worker process 34
[root@master ~]#

指定pod容器

方法见上面bash的用法吧,方法都一样,就加个参数-c 容器名 罢了

pod的生命周期【优雅的关闭】

[root@master ~]# kubectl explain pods.spec | egrep -A 9 terminationGracePeriodSeconds
   terminationGracePeriodSeconds        <integer>
     Optional duration in seconds the pod needs to terminate gracefully. May be
     decreased in delete request. Value must be non-negative integer. The value
     zero indicates stop immediately via the kill signal (no opportunity to shut
     down). If this value is nil, the default grace period will be used instead.
     The grace period is the duration in seconds after the processes running in
     the pod are sent a termination signal and the time when the processes are
     forcibly halted with a kill signal. Set this value longer than the expected
     cleanup time for your process. Defaults to 30 seconds.

[root@master ~]#
[root@master ~]# cp pod2.yaml  pod3.yaml
[root@master ~]# vim pod3.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod3
  name: pod3
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  - image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 10000"]
    name: c2
    resources: {}
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
~
~
~
~
"pod3.yaml" 22L, 417C written                                    
[root@master ~]# kubectl apply -f pod3.yaml 
pod/pod3 created
[root@master ~]# kubectl get pods
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          102m
pod2   2/2     Running   0          25m
pod3   2/2     Running   0          5s
[root@master ~]# 
[root@master ~]# kubectl delete pod pod3
pod "pod3" deleted
[root@master ~]# 

pod钩子【pod hook】

说明

spec:
  - image:**
    ...
    #下面的为钩子的全部语法了
	lifecycle:
	  postStart:
	    exec:
	      command: ["/bin/sh","-c","执行命令"]
	  preStop:
	    exec:
	      command: ["/bin/sh","-c","执行命令"]

demo

[root@master ~]# cat pod4.yaml
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod4
  name: pod4
spec:
  terminationGracePeriodSeconds: 600
  containers:
  - image: nginx
    command: ["sh","-c","data > /tmp/aa.txt ; sleep 10000"]
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c","data > /tmp/bb.txt"]
      preStop:
          exec:
            command: ["/bin/sh","-c","data >> /tmp/bb.txt ; sleep 100"]
  dnsPolicy: ClusterFirst
  restartPolicy: Always
status: {}
[root@master ~]# 

#  terminationGracePeriodSeconds: 600 ——宽恕期设置为600
#  command: ["sh","-c","date > /tmp/aa.txt ; sleep 10000"] —— 主进程改为这个。
#  command: ["/bin/sh","-c","date > /tmp/bb.txt"]——容器创建时执行这个【和上面主进程同时运行】
#  command: ["/bin/sh","-c","date >> /tmp/bb.txt ; sleep 100"]——容器关闭【删除】时执行这个
[root@master ~]# kubectl apply -f pod4.yaml 
pod/pod4 created
[root@master ~]# 
[root@master ~]# kubectl exec -it pod4 -- bash
root@pod4:/# 
root@pod4:/# cat /tmp/aa.txt 
Mon Jul 26 09:10:48 UTC 2021
root@pod4:/# 
root@pod4:/# cat /tmp/bb.txt 
Mon Jul 26 09:10:48 UTC 2021
root@pod4:/# 
root@pod4:/# 
root@pod4:/# exit
exit
[root@master ~]#
[root@master ~]# kubectl get pod
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          3d6h
pod2   2/2     Running   27         3d4h
pod4   1/1     Running   0          3m52s
[root@master ~]# kubectl delete pod pod4
pod "pod4" deleted
#卡在这里的,这时候我们重新打开一个终端,并进入这个bash里面


[root@master ~]# kubectl exec -it pod4 -- bash
root@pod4:/# cat /tmp/bb.txt 
Mon Jul 26 09:10:48 UTC 2021
Mon Jul 26 09:14:45 UTC 2021
root@pod4:/# 
root@pod4:/# exit
exit
[root@master ~]# 
[root@master ~]# kubectl get pod
NAME   READY   STATUS        RESTARTS   AGE
pod1   1/1     Running       0          3d6h
pod2   2/2     Running       27         3d4h
pod4   1/1     Terminating   0          5m43s
[root@master ~]# 

# 许久之后
[root@master ~]# kubectl get pod | tail -n 1
pod4   1/1     Terminating   0          8m52s
[root@master ~]# 

#我们上面是3分钟开始删除的,现在8分了,过去了5分钟,600秒马上到了,这个容器也该被删除了,再等一分钟
# 回到刚删除的界面,可以看到删除结束了,同时pod4也没了

[root@master ~]# kubectl delete pod pod4
pod "pod4" deleted
[root@master ~]# 
[root@master ~]# kubectl get pod
NAME   READY   STATUS    RESTARTS   AGE
pod1   1/1     Running   0          3d6h
pod2   2/2     Running   27         3d5h
[root@master ~]# 
...
   preStop:
          exec:
            command: ["/bin/sh","-c","/usr/sbin/nginx -s quit"]
...

初始化pod

说明

spec:
...
  initContainers:
  - name: initc1 #自定义名称
    image: nginx #镜像名称
    imagePullPolicy: IfNotPresent #镜像策略
    command: ["sh","-c","sleep 20"] #command
...
[root@master ~]# kubectl apply -f pod5.yaml 
pod/pod5 created
[root@master ~]# 
[root@master ~]# kubectl get pods -o wide
NAME   READY   STATUS     RESTARTS   AGE   IP               NODE    NOMINATED NODE   READINESS GATES
pod5   0/1     Init:0/1   0          8s    10.244.166.138   node1   <none>           <none>
[root@master ~]# 
[root@master ~]# ssh node1
root@node1's password: 
Last login: Tue Jul 27 10:43:30 2021 from master
[root@node1 ~]# 
[root@node1 ~]# docker ps | grep pause
f172aa85d2f1   registry.aliyuncs.com/google_containers/pause:3.4.1   "/pause"                 2 minutes ago        Up 2 minutes                  k8s_POD_pod5_pod-1_5d3283f7-0fb2-41d2-9a3f-d586ad92ddb7_0
9eb01589f988   registry.aliyuncs.com/google_containers/pause:3.4.1   "/pause"                 8 days ago           Up 8 days                     k8s_POD_calico-node-zl42z_kube-system_7d504cb1-790f-407f-b5f7-f292cef949a5_1
be2b39468acd   registry.aliyuncs.com/google_containers/pause:3.4.1   "/pause"                 8 days ago           Up 8 days                     k8s_POD_kube-proxy-7nqfv_kube-system_cb31c4f7-7dcc-4632-b281-907cef422133_1
[root@node1 ~]# 


#一个pod对应一个pause容器
# 也就是说,运行的容器出了pod本身,还会有一个pause存在
[root@node1 ~]# docker ps | grep pod5
69e1009f9b59   d1a364dc548d                                          "/docker-entrypoint.…"   3 minutes ago   Up 3 minutes             k8s_c1_pod5_pod-1_5d3283f7-0fb2-41d2-9a3f-d586ad92ddb7_0
f172aa85d2f1   registry.aliyuncs.com/google_containers/pause:3.4.1   "/pause"                 3 minutes ago   Up 3 minutes             k8s_POD_pod5_pod-1_5d3283f7-0fb2-41d2-9a3f-d586ad92ddb7_0
[root@node1 ~]#

规则

demo

[root@master ~]# cat pod5.yaml 
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod5
  name: pod5
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  initContainers:
  - name: initc1
    image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 20"]
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}
[root@master ~]# 
[root@master ~]# kubectl apply -f pod5.yaml 
pod/pod5 created
[root@master ~]# kubectl get pods
NAME   READY   STATUS     RESTARTS   AGE
pod1   1/1     Running    0          3d7h
pod2   2/2     Running    28         3d6h
pod5   0/1     Init:0/1   0          3s
[root@master ~]# 
[root@master ~]# kubectl get pods | tail -n 1 
pod5   0/1     Init:0/1   0          15s
[root@master ~]# 
[root@master ~]# kubectl get pods | tail -n 1 
pod5   0/1     Init:0/1   0          17s
[root@master ~]# kubectl get pods | tail -n 1 
pod5   0/1     Init:0/1   0          20s
[root@master ~]# kubectl get pods | tail -n 1 
pod5   0/1     Init:0/1   0          22s
[root@master ~]# kubectl get pods | tail -n 1 
pod5   1/1     Running   0          24s
[root@master ~]# 
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod5
  name: pod5
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  initContainers:
  - name: initc1
    image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 20"]
  initContainers:
  - name: initc1
    image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 20"]
  initContainers:
  - name: initc1
    image: nginx
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","sleep 20"]
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}

扩展demo【修改内核参数】

[root@node1 ~]# docker pull alpine

# 下载完以后有如下镜像
[root@node1 ~]# docker images | grep alpine
alpine                                                            latest     d4ff818577bc   5 weeks ago     5.6MB
[root@node1 ~]#
[root@master ~]# cat pod6.yaml 
apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: pod6
  name: pod6
spec:
  terminationGracePeriodSeconds: 0
  containers:
  - image: nginx
    imagePullPolicy: IfNotPresent
    name: c1
    resources: {}
  initContainers:
  - name: initc1
    image: alpine
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","/sbin/sysctl -w vm.swappiness=0"]
    securityContext:
      privileged: true
  dnsPolicy: ClusterFirst
  restartPolicy: Never
status: {}
[root@master ~]# 


#下面为解释哈
 initContainers: #定义初始化内容
  - name: initc1 #自定义名称
    image: alpine #镜像
    imagePullPolicy: IfNotPresent #容器模式
    command: ["sh","-c","/sbin/sysctl -w vm.swappiness=0"]
    securityContext: #这个就是允许容器修改主机内核参数的选项
      privileged: true #true为允许修改
[root@master ~]# kubectl apply -f pod6.yaml 
pod/pod6 created
# 下面这个命令是查看这个pod运行在哪个节点上的
[root@master ~]# kubectl get pods -o wide | grep pod6
pod6   1/1     Running   0          80s     10.244.166.137   node1   <none>           <none>
[root@master ~]#
[root@master ~]# ssh node1
root@node1's password: 
Last login: Tue Jul 27 10:13:10 2021 from master
[root@node1 ~]# 
[root@node1 ~]# cat /proc/sys/vm/swappiness 
0
[root@node1 ~]#
[root@master ~]# kubectl get pod -o wide | grep pod5
pod5   1/1     Running   0          16h     10.244.104.14    node2   <none>           <none>
[root@master ~]# 
[root@master ~]# ssh node2
root@node2's password: 
Last login: Tue Jul 27 10:15:23 2021 from master
[root@node2 ~]# cat /proc/sys/vm/swappiness
30
[root@node2 ~]# 

扩展demo【容器数据同步到本地,在获取本地数据】

[root@node2 ~]# docker pull busybox
[root@node2 ~]# docker images | grep bus
busybox                                                           latest     69593048aa3a   7 weeks ago     1.24MB
[root@node2 ~]# 
[root@node2 ~]# exit
logout
Connection to node2 closed.
[root@master ~]# cat pod7.yaml 
apiVersion: v1
kind: Pod
metadata:
  name: myapp-pod
  labels:
    app: myapp
spec:
  terminationGracePeriodSeconds: 0
  volumes:
  - name: nodedir
    emptyDir: {}
  containers:
  - name: myapp-container
    image: nginx
    imagePullPolicy: IfNotPresent
    volumeMounts:
    - name: nodedir
      mountPath: "/xx"
  initContainers:
  - name: initc1
    image: busybox
    imagePullPolicy: IfNotPresent
    command: ["sh","-c","touch /node-dir/aa.txt"]
    volumeMounts:
    - name: nodedir
      mountPath: "/node-dir"
[root@master ~]# 
[root@master ~]# kubectl apply -f pod7.yaml
pod/myapp-pod created
[root@master ~]# kubectl get pods
NAME        READY   STATUS    RESTARTS   AGE
myapp-pod   1/1     Running   0          64s
[root@master ~]# kubectl exec -it myapp-pod -- bash
Defaulted container "myapp-container" out of: myapp-container, initc1 (init)
root@myapp-pod:/# 
root@myapp-pod:/# ls /xx
aa.txt
root@myapp-pod:/# 
root@myapp-pod:/# exit
exit
command terminated with exit code 1
[root@master ~]#

标签:11,kubectl,容器,label,master,pod,root,pod1
来源: https://blog.csdn.net/cuichongxin/article/details/118763330