YAML file for K8S

Standard
#test-pod 
apiVersion: v1 #指定api版本,此值必须在kubectl apiversion中   
kind: Pod #指定创建资源的角色/类型   
metadata: #资源的元数据/属性   
  name: test-pod #资源的名字,在同一个namespace中必须唯一   
  labels: #设定资源的标签 
    k8s-app: apache   
    version: v1   
    kubernetes.io/cluster-service: "true"   
  annotations:            #自定义注解列表   
    - name: String        #自定义注解名字   
spec: #specification of the resource content 指定该资源的内容   
  restartPolicy: Always #表明该容器一直运行,默认k8s的策略,在此容器退出后,会立即创建一个相同的容器   
  nodeSelector:     #节点选择,先给主机打标签kubectl label nodes kube-node1 zone=node1   
    zone: node1   
  containers:   
  - name: test-pod #容器的名字   
    image: 10.192.21.18:5000/test/chat:latest #容器使用的镜像地址   
    imagePullPolicy: Never #三个选择Always、Never、IfNotPresent,每次启动时检查和更新(从registery)images的策略, 
                           # Always,每次都检查 
                           # Never,每次都不检查(不管本地是否有) 
                           # IfNotPresent,如果本地有就不检查,如果没有就拉取 
    command: ['sh'] #启动容器的运行命令,将覆盖容器中的Entrypoint,对应Dockefile中的ENTRYPOINT   
    args: ["$(str)"] #启动容器的命令参数,对应Dockerfile中CMD参数   
    env: #指定容器中的环境变量   
    - name: str #变量的名字   
      value: "/etc/run.sh" #变量的值   
    resources: #资源管理 
      requests: #容器运行时,最低资源需求,也就是说最少需要多少资源容器才能正常运行   
        cpu: 0.1 #CPU资源(核数),两种方式,浮点数或者是整数+m,0.1=100m,最少值为0.001核(1m) 
        memory: 32Mi #内存使用量   
      limits: #资源限制   
        cpu: 0.5   
        memory: 1000Mi   
    ports:   
    - containerPort: 80 #容器开发对外的端口 
      name: httpd  #名称 
      protocol: TCP   
    livenessProbe: #pod内容器健康检查的设置 
      httpGet: #通过httpget检查健康,返回200-399之间,则认为容器正常   
        path: / #URI地址   
        port: 80   
        #host: 127.0.0.1 #主机地址   
        scheme: HTTP   
      initialDelaySeconds: 180 #表明第一次检测在容器启动后多长时间后开始   
      timeoutSeconds: 5 #检测的超时时间   
      periodSeconds: 15  #检查间隔时间   
      #也可以用这种方法   
      #exec: 执行命令的方法进行监测,如果其退出码不为0,则认为容器正常   
      #  command:   
      #    - cat   
      #    - /tmp/health   
      #也可以用这种方法   
      #tcpSocket: //通过tcpSocket检查健康    
      #  port: number    
    lifecycle: #生命周期管理   
      postStart: #容器运行之前运行的任务   
        exec:   
          command:   
            - 'sh'   
            - 'yum upgrade -y'   
      preStop:#容器关闭之前运行的任务   
        exec:   
          command: ['service httpd stop']   
    volumeMounts:  #挂载持久存储卷 
    - name: volume #挂载设备的名字,与volumes[*].name 需要对应     
      mountPath: /data #挂载到容器的某个路径下   
      readOnly: True   
  volumes: #定义一组挂载设备   
  - name: volume #定义一个挂载设备的名字   
    #meptyDir: {}   
    hostPath:   
      path: /opt #挂载设备类型为hostPath,路径为宿主机下的/opt,这里设备类型支持很多种 
    #nfs

vim nginx-deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.10
        ports:
        - containerPort: 80
ye@ye:~/test$ kubectl create -f nginx-deployment.yaml
deployment.apps/nginx-deployment created
ye@ye:~/test$ kubectl get pod --show-labels
NAME                                READY   STATUS    RESTARTS   AGE     LABELS
guestbook-ui-85985d774c-dgbxq       1/1     Running   2          2d15h   app=guestbook-ui,pod-template-hash=85985d774c
nginx-deployment-748755bf57-4swcz   1/1     Running   0          18s     app=nginx,pod-template-hash=748755bf57
nginx-deployment-748755bf57-kh7wz   1/1     Running   0          18s     app=nginx,pod-template-hash=748755bf57
nginx-deployment-748755bf57-7ldgn   1/1     Running   0          18s     app=nginx,pod-template-hash=748755bf57
ye@ye:~/test$ kubectl get pod -l app=nginx
NAME                                READY   STATUS    RESTARTS   AGE
nginx-deployment-748755bf57-4swcz   1/1     Running   0          32s
nginx-deployment-748755bf57-kh7wz   1/1     Running   0          32s
nginx-deployment-748755bf57-7ldgn   1/1     Running   0          32s
ye@ye:~/test$ kubectl describe rs nginx-deployment
Name:           nginx-deployment-748755bf57
Namespace:      default
Selector:       app=nginx,pod-template-hash=748755bf57
Labels:         app=nginx
                pod-template-hash=748755bf57
Annotations:    deployment.kubernetes.io/desired-replicas: 3
                deployment.kubernetes.io/max-replicas: 4
                deployment.kubernetes.io/revision: 1
Controlled By:  Deployment/nginx-deployment
Replicas:       3 current / 3 desired
Pods Status:    3 Running / 0 Waiting / 0 Succeeded / 0 Failed
Pod Template:
  Labels:  app=nginx
           pod-template-hash=748755bf57
  Containers:
   nginx:
    Image:        nginx:1.10
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Events:
  Type    Reason            Age   From                   Message
  ----    ------            ----  ----                   -------
  Normal  SuccessfulCreate  46s   replicaset-controller  Created pod: nginx-deployment-748755bf57-kh7wz
  Normal  SuccessfulCreate  46s   replicaset-controller  Created pod: nginx-deployment-748755bf57-7ldgn
  Normal  SuccessfulCreate  46s   replicaset-controller  Created pod: nginx-deployment-748755bf57-4swcz
 
ye@ye:~/test$ kubectl describe pod nginx-deployment-748755bf57-kh7wz
Name:         nginx-deployment-748755bf57-kh7wz
Namespace:    default
Priority:     0
Node:         ye/192.168.8.130
Start Time:   Tue, 28 Sep 2021 02:32:19 +0000
Labels:       app=nginx
              pod-template-hash=748755bf57
Annotations:  cni.projectcalico.org/podIP: 10.1.132.84/32
              cni.projectcalico.org/podIPs: 10.1.132.84/32
Status:       Running
IP:           10.1.132.84
IPs:
  IP:           10.1.132.84
Controlled By:  ReplicaSet/nginx-deployment-748755bf57
Containers:
  nginx:
    Container ID:   containerd://c619fddebde1fcbdaba3a6b69ee8c47eca9ec46e4771517e7ce141cd0d521228
    Image:          nginx:1.10
    Image ID:       docker.io/library/nginx@sha256:6202beb06ea61f44179e02ca965e8e13b961d12640101fca213efbfd145d7575
    Port:           80/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 28 Sep 2021 02:32:23 +0000
    Ready:          True
    Restart Count:  0
    Environment:    <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from kube-api-access-cl2h8 (ro)
Conditions:
  Type              Status
  Initialized       True 
  Ready             True 
  ContainersReady   True 
  PodScheduled      True 
Volumes:
  kube-api-access-cl2h8:
    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  87s   default-scheduler  Successfully assigned default/nginx-deployment-748755bf57-kh7wz to ye
  Normal  Pulled     84s   kubelet            Container image "nginx:1.10" already present on machine
  Normal  Created    84s   kubelet            Created container nginx
  Normal  Started    83s   kubelet            Started container nginx
ye@ye:~/test$ kubectl set image deploy/nginx-deployment nginx=nginx:1.11
deployment.apps/nginx-deployment image updated
ye@ye:~/test$ kubectl rollout status deploy/nginx-deployment
deployment "nginx-deployment" successfully rolled out
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment
deployment.apps/nginx-deployment 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
 
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment --revision=1
deployment.apps/nginx-deployment with revision #1
Pod Template:
  Labels:       app=nginx
        pod-template-hash=748755bf57
  Containers:
   nginx:
    Image:      nginx:1.10
    Port:       80/TCP
    Host Port:  0/TCP
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>
 
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment --revision=2
deployment.apps/nginx-deployment with revision #2
Pod Template:
  Labels:       app=nginx
        pod-template-hash=897f8f586
  Containers:
   nginx:
    Image:      nginx:1.11
    Port:       80/TCP
    Host Port:  0/TCP
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>
 
ye@ye:~/test$ kubectl edit deploy/nginx-deployment
# Please edit the object below. Lines beginning with a '#' will be ignored,
# and an empty file will abort the edit. If an error occurs while saving this file will be
# reopened with the relevant failures.
#
apiVersion: apps/v1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "2"
  creationTimestamp: "2021-09-28T02:32:19Z"
  generation: 2
  name: nginx-deployment
  namespace: default
  resourceVersion: "92192"
  selfLink: /apis/apps/v1/namespaces/default/deployments/nginx-deployment
  uid: a7416ec4-5569-4e6a-939c-9662f7acd232
spec:
  progressDeadlineSeconds: 600
  replicas: 3
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: nginx
  strategy:
    rollingUpdate:
      maxSurge: 25%
      maxUnavailable: 25%
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: nginx
    spec:
      containers:
      - image: nginx:1.12
        imagePullPolicy: IfNotPresent
        name: nginx
        ports:
        - containerPort: 80
          protocol: TCP
        resources: {}
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 3
  conditions:
  - lastTransitionTime: "2021-09-28T02:32:24Z"
    lastUpdateTime: "2021-09-28T02:32:24Z"
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  - lastTransitionTime: "2021-09-28T02:32:19Z"
    lastUpdateTime: "2021-09-28T02:34:40Z"
    message: ReplicaSet "nginx-deployment-897f8f586" has successfully progressed.
    reason: NewReplicaSetAvailable
    status: "True"
    type: Progressing
  observedGeneration: 2
  readyReplicas: 3
  replicas: 3
  updatedReplicas: 3
~
~
~
~
"/tmp/kubectl-edit-ik3mc.yaml" 68L, 1921C written                                                                                                                                                                       
deployment.apps/nginx-deployment edited
ye@ye:~/test$ kubectl rollout status deploy/nginx-deployment
Waiting for deployment "nginx-deployment" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "nginx-deployment" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "nginx-deployment" rollout to finish: 2 out of 3 new replicas have been updated...
Waiting for deployment "nginx-deployment" rollout to finish: 1 old replicas are pending termination...
Waiting for deployment "nginx-deployment" rollout to finish: 1 old replicas are pending termination...
deployment "nginx-deployment" successfully rolled out
ye@ye:~/test$ kubectl get pod
NAME                               READY   STATUS    RESTARTS   AGE
guestbook-ui-85985d774c-dgbxq      1/1     Running   2          2d15h
nginx-deployment-f77774fc5-wlr8g   1/1     Running   0          41s
nginx-deployment-f77774fc5-r8fll   1/1     Running   0          24s
nginx-deployment-f77774fc5-v8bg8   1/1     Running   0          20s
ye@ye:~/test$ kubectl scale deploy/nginx-deployment --replicas=5
deployment.apps/nginx-deployment scaled
ye@ye:~/test$ kubectl get pod
NAME                               READY   STATUS    RESTARTS   AGE
guestbook-ui-85985d774c-dgbxq      1/1     Running   2          2d15h
nginx-deployment-f77774fc5-wlr8g   1/1     Running   0          69s
nginx-deployment-f77774fc5-r8fll   1/1     Running   0          52s
nginx-deployment-f77774fc5-v8bg8   1/1     Running   0          48s
nginx-deployment-f77774fc5-sgr99   1/1     Running   0          7s
nginx-deployment-f77774fc5-xqgfr   1/1     Running   0          7s

vim nginx-service.yaml

apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  labels:
    app: nginx
spec:
  ports:
  - port: 88
    targetPort: 80
  selector:
    app: nginx
ye@ye:~/test$ kubectl create -f nginx-service.yaml
service/nginx-service created
ye@ye:~/test$ kubectl get svc/nginx-service
NAME            TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)   AGE
nginx-service   ClusterIP   10.152.183.228   <none>        88/TCP    16s
ye@ye:~/test$ curl 10.152.183.228
^C
ye@ye:~/test$ curl 10.152.183.228:88
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
 
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
 
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
ye@ye:~/test$ kubectl describe svc/nginx-service
Name:              nginx-service
Namespace:         default
Labels:            app=nginx
Annotations:       <none>
Selector:          app=nginx
Type:              ClusterIP
IP Family Policy:  SingleStack
IP Families:       IPv4
IP:                10.152.183.228
IPs:               10.152.183.228
Port:              <unset>  88/TCP
TargetPort:        80/TCP
Endpoints:         10.1.132.83:80,10.1.132.86:80,10.1.132.88:80 + 2 more...
Session Affinity:  None
Events:            <none>
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment
deployment.apps/nginx-deployment 
REVISION  CHANGE-CAUSE
1         <none>
2         <none>
3         <none>
 
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment --revision=3
deployment.apps/nginx-deployment with revision #3
Pod Template:
  Labels:       app=nginx
        pod-template-hash=f77774fc5
  Containers:
   nginx:
    Image:      nginx:1.12
    Port:       80/TCP
    Host Port:  0/TCP
    Environment:        <none>
    Mounts:     <none>
  Volumes:      <none>
 
ye@ye:~/test$ kubectl rollout undo deploy/nginx-deployment
deployment.apps/nginx-deployment rolled back
ye@ye:~/test$ kubectl describe deploy/nginx-deployment
Name:                   nginx-deployment
Namespace:              default
CreationTimestamp:      Tue, 28 Sep 2021 02:32:19 +0000
Labels:                 <none>
Annotations:            deployment.kubernetes.io/revision: 4
Selector:               app=nginx
Replicas:               5 desired | 5 updated | 5 total | 5 available | 0 unavailable
StrategyType:           RollingUpdate
MinReadySeconds:        0
RollingUpdateStrategy:  25% max unavailable, 25% max surge
Pod Template:
  Labels:  app=nginx
  Containers:
   nginx:
    Image:        nginx:1.11
    Port:         80/TCP
    Host Port:    0/TCP
    Environment:  <none>
    Mounts:       <none>
  Volumes:        <none>
Conditions:
  Type           Status  Reason
  ----           ------  ------
  Available      True    MinimumReplicasAvailable
  Progressing    True    NewReplicaSetAvailable
OldReplicaSets:  <none>
NewReplicaSet:   nginx-deployment-897f8f586 (5/5 replicas created)
Events:
  Type    Reason             Age                  From                   Message
  ----    ------             ----                 ----                   -------
  Normal  ScalingReplicaSet  12m                  deployment-controller  Scaled up replica set nginx-deployment-748755bf57 to 3
  Normal  ScalingReplicaSet  10m                  deployment-controller  Scaled up replica set nginx-deployment-897f8f586 to 1
  Normal  ScalingReplicaSet  10m                  deployment-controller  Scaled down replica set nginx-deployment-748755bf57 to 2
  Normal  ScalingReplicaSet  10m                  deployment-controller  Scaled up replica set nginx-deployment-897f8f586 to 2
  Normal  ScalingReplicaSet  10m                  deployment-controller  Scaled down replica set nginx-deployment-748755bf57 to 1
  Normal  ScalingReplicaSet  10m                  deployment-controller  Scaled down replica set nginx-deployment-748755bf57 to 0
  Normal  ScalingReplicaSet  8m11s                deployment-controller  Scaled up replica set nginx-deployment-f77774fc5 to 1
  Normal  ScalingReplicaSet  7m54s                deployment-controller  Scaled down replica set nginx-deployment-897f8f586 to 2
  Normal  ScalingReplicaSet  18s (x2 over 10m)    deployment-controller  Scaled up replica set nginx-deployment-897f8f586 to 3
  Normal  ScalingReplicaSet  3s (x12 over 7m54s)  deployment-controller  (combined from similar events): Scaled down replica set nginx-deployment-f77774fc5 to 0
ye@ye:~/test$ kubectl rollout history deploy/nginx-deployment
deployment.apps/nginx-deployment 
REVISION  CHANGE-CAUSE
1         <none>
3         <none>
4         <none>
 
ye@ye:~/test$ kubectl rollout undo deploy/nginx-deployment --to-revision=1
deployment.apps/nginx-deployment rolled back
ye@ye:~/test$ kubectl delete -f nginx-deployment.yaml
deployment.apps "nginx-deployment" deleted
ye@ye:~/test$ kubectl delete -f nginx-service.yaml
service "nginx-service" deleted
# yaml格式的pod定义文件完整内容:
apiVersion: v1       #必选,版本号,例如v1
kind: Pod       #必选,Pod
metadata:       #必选,元数据
  name: string       #必选,Pod名称
  namespace: string    #必选,Pod所属的命名空间
  labels:      #自定义标签
    - name: string     #自定义标签名字
  annotations:       #自定义注释列表
    - name: string
spec:         #必选,Pod中容器的详细定义
  containers:      #必选,Pod中容器列表
  - name: string     #必选,容器名称
    image: string    #必选,容器的镜像名称
    imagePullPolicy: [Always | Never | IfNotPresent] #获取镜像的策略 Alawys表示下载镜像 IfnotPresent表示优先使用本地镜像,否则下载镜像,Nerver表示仅使用本地镜像
    command: [string]    #容器的启动命令列表,如不指定,使用打包时使用的启动命令
    args: [string]     #容器的启动命令参数列表
    workingDir: string     #容器的工作目录
    volumeMounts:    #挂载到容器内部的存储卷配置
    - name: string     #引用pod定义的共享存储卷的名称,需用volumes[]部分定义的的卷名
      mountPath: string    #存储卷在容器内mount的绝对路径,应少于512字符
      readOnly: boolean    #是否为只读模式
    ports:       #需要暴露的端口库号列表
    - name: string     #端口号名称
      containerPort: int   #容器需要监听的端口号
      hostPort: int    #容器所在主机需要监听的端口号,默认与Container相同
      protocol: string     #端口协议,支持TCP和UDP,默认TCP
    env:       #容器运行前需设置的环境变量列表
    - name: string     #环境变量名称
      value: string    #环境变量的值
    resources:       #资源限制和请求的设置
      limits:      #资源限制的设置
        cpu: string    #Cpu的限制,单位为core数,将用于docker run --cpu-shares参数
        memory: string     #内存限制,单位可以为Mib/Gib,将用于docker run --memory参数
      requests:      #资源请求的设置
        cpu: string    #Cpu请求,容器启动的初始可用数量
        memory: string     #内存清楚,容器启动的初始可用数量
    livenessProbe:     #对Pod内个容器健康检查的设置,当探测无响应几次后将自动重启该容器,检查方法有exec、httpGet和tcpSocket,对一个容器只需设置其中一种方法即可
      exec:      #对Pod容器内检查方式设置为exec方式
        command: [string]  #exec方式需要制定的命令或脚本
      httpGet:       #对Pod内个容器健康检查方法设置为HttpGet,需要制定Path、port
        path: string
        port: number
        host: string
        scheme: string
        HttpHeaders:
        - name: string
          value: string
      tcpSocket:     #对Pod内个容器健康检查方式设置为tcpSocket方式
         port: number
       initialDelaySeconds: 0  #容器启动完成后首次探测的时间,单位为秒
       timeoutSeconds: 0   #对容器健康检查探测等待响应的超时时间,单位秒,默认1秒
       periodSeconds: 0    #对容器监控检查的定期探测时间设置,单位秒,默认10秒一次
       successThreshold: 0
       failureThreshold: 0
       securityContext:
         privileged:false
    restartPolicy: [Always | Never | OnFailure]#Pod的重启策略,Always表示一旦不管以何种方式终止运行,kubelet都将重启,OnFailure表示只有Pod以非0退出码退出才重启,Nerver表示不再重启该Pod
    nodeSelector: obeject  #设置NodeSelector表示将该Pod调度到包含这个label的node上,以key:value的格式指定
    imagePullSecrets:    #Pull镜像时使用的secret名称,以key:secretkey格式指定
    - name: string
    hostNetwork:false      #是否使用主机网络模式,默认为false,如果设置为true,表示使用宿主机网络
    volumes:       #在该pod上定义共享存储卷列表
    - name: string     #共享存储卷名称 (volumes类型有很多种)
      emptyDir: {}     #类型为emtyDir的存储卷,与Pod同生命周期的一个临时目录。为空值
      hostPath: string     #类型为hostPath的存储卷,表示挂载Pod所在宿主机的目录
        path: string     #Pod所在宿主机的目录,将被用于同期中mount的目录
      secret:      #类型为secret的存储卷,挂载集群与定义的secre对象到容器内部
        scretname: string  
        items:     
        - key: string
          path: string
      configMap:     #类型为configMap的存储卷,挂载预定义的configMap对象到容器内部
        name: string
        items:
        - key: string

照着这里敲一遍: https://blog.csdn.net/BigData_Mining/article/details/88535356

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.