Kubernetes 基础学习和概念;PVC/Configmap/service/deploment/

Kubernetes-doc | kubernetes-doc

  • 教程 | Kubernetes
  • k8s - 随笔分类 - 邹邹很busy。 - 博客园
apiVersion: apps/v1  # 指定api版本,此值必须在kubectl api-versions中  
kind: Deployment  # 指定创建资源的角色/类型   
metadata:  # 资源的元数据/属性 
  name: demo  # 资源的名字,在同一个namespace中必须唯一
  namespace: default # 部署在哪个namespace中
  labels:  # 设定资源的标签
    app: demo
    version: stable
spec: # 资源规范字段
  replicas: 1 # 声明副本数目
  revisionHistoryLimit: 3 # 保留历史版本
  selector: # 选择器
    matchLabels: # 匹配标签
      app: demo
      version: stable
  strategy: # 策略
    rollingUpdate: # 滚动更新
      maxSurge: 30% # 最大额外可以存在的副本数,可以为百分比,也可以为整数
      maxUnavailable: 30% # 在更新过程中能够进入不可用状态的 Pod 的最大值,可以为百分比,也可以为整数
    type: RollingUpdate # 滚动更新策略
  template: # 模版
    metadata: # 资源的元数据/属性 
      annotations: # 自定义注解列表
        sidecar.istio.io/inject: "false" # 自定义注解名字
      labels: # 设定资源的标签
        app: demo
        version: stable
    spec: # 资源规范字段
      containers:
      - name: demo # 容器的名字   
        image: demo:v1 # 容器使用的镜像地址   
        imagePullPolicy: IfNotPresent 
        # 每次Pod启动拉取镜像策略,三个选择 Always、Never、IfNotPresent
        # Always,每次都检查;
        # Never,每次都不检查(不管本地是否有);
        # IfNotPresent,如果本地有就不检查,如果没有就拉取
        resources: # 资源管理
          limits: # 最大使用
            cpu: 300m # CPU,1核心 = 1000m
            memory: 500Mi # 内存,1G = 1000Mi
          requests:  # 容器运行时,最低资源需求,也就是说最少需要多少资源容器才能正常运行
            cpu: 100m
            memory: 100Mi
        livenessProbe: # pod 内部健康检查的设置
          httpGet: # 通过httpget检查健康,返回200-399之间,则认为容器正常
            path: /healthCheck # URI地址
            port: 8080 # 端口
            scheme: HTTP # 协议
            # host: 127.0.0.1 # 主机地址
          initialDelaySeconds: 30 # 表明第一次检测在容器启动后多长时间后开始
          timeoutSeconds: 5 # 检测的超时时间
          periodSeconds: 30 # 检查间隔时间
          successThreshold: 1 # 成功门槛
          failureThreshold: 5 # 失败门槛,连接失败5次,pod杀掉,重启一个新的pod
        readinessProbe: # Pod 准备服务健康检查设置
          httpGet:
            path: /healthCheck
            port: 8080
            scheme: HTTP
          initialDelaySeconds: 30
          timeoutSeconds: 5
          periodSeconds: 10
          successThreshold: 1
          failureThreshold: 5
      	#也可以用这种方法   
      	#exec: 执行命令的方法进行监测,如果其退出码不为0,则认为容器正常   
      	#  command:   
      	#    - cat   
      	#    - /tmp/health   
      	#也可以用这种方法   
      	#tcpSocket: # 通过tcpSocket检查健康  
      	#  port: number 
        ports:
          - name: http # 名称
            containerPort: 8080 # 容器开发对外的端口 
            protocol: TCP # 协议
      imagePullSecrets: # 镜像仓库拉取密钥
        - name: harbor-certification
      affinity: # 亲和性调试
        nodeAffinity: # 节点亲和力
          requiredDuringSchedulingIgnoredDuringExecution: # pod 必须部署到满足条件的节点上
            nodeSelectorTerms: # 节点满足任何一个条件就可以
            - matchExpressions: # 有多个选项,则只有同时满足这些逻辑选项的节点才能运行 pod
              - key: beta.kubernetes.io/arch
                operator: In
                values:
                - amd64

service:


====================================类型:
ClusterIp:默认类型,自动分配一个仅Cluster内部可以访问的娜IP
NodePort:在ClusterIP基础上为Service在每台机器上绑定一作口,这样就可以通过NodePort来访问该服努
LoadBalancer:在NodePort的基础上,侑助cloud provider创建一个外部负载均衡器,并将请热专发 到:NodePort
ExternalName:把集群外部的服努引入到集群内部来,在集群内部直接使用。没有任何类型代理被创建, 这只有kubernetes 1.7或更高版本的kube-dns才支持


====================================代理模式:
1、kube-proxy   会监听apiserver中Service的变化, 并写入相关iptables 规则,请求会通过用户空间进入iptables,进入kube-proxy,然后代理转发请求后后端Pod,默认使用 轮询算法,性能很低,一般不用

2、Iptables:(小到中等规模的集群(例如少于50个节点,几百个Service,几千个Pod),并且不需要特别高级的负载均衡功能时,iptables是一个很好的选择)

3、IPVS :LVS是Linux Virtual Server的简称;LVS的IP负载均衡技术是通过IPVS模块实现的。IPVS模块是LVS集群的核心软件模块,它安装在LVS集群作为负载均衡的主节点上,虚拟出一个IP地址和端口对外提供服务。用户通过访问这个虚拟服务(VS),然后访问请求由负载均衡器(LB)调度到后端真实服务器(RS)中,由RS实际处理用户的请求给返回响应。

并提供了多种负载均衡算法:

rr: round-robin(轮训)
lc: least connection (最小打开的连接数)
dh: destination hashing(目标哈希)
sh: source hashing(源哈希)
sed: shortest expected delay(最短期望延迟)
nq: never queue(不排队调度)



在kube-proxy的配置文件中设置mode: "ipvs"来启用IPVS模式。
 
apiVersion: kubeproxy.config.k8s.io/v1alpha1
kind: KubeProxyConfiguration
mode: "ipvs"


=================================使用

apiVersion: v1
kind: Service
metadata:
  name: nms
  labels:
    name: nms
  namespace: vcs
 #annotations: # prometheus 自动采集用的
    #prometheus.io/scrape: 'true'
spec:
  type: ClusterIP
  ports:
    - protocol: TCP
      targetPort: 9888 # 指定后端Pod应该监听的端口
      port: 9888 # Service对外提供的接口; 从集群内部访问这个Service
      name: http
  selector:
    app: nms


apiVersion: v1
kind: Service
metadata:
  name: apigateway
  namespace: vcs
  labels:
    name: apigateway
spec:
  type: NodePort
  ports:
    - port: 7777
      protocol: TCP
      targetPort: 7777
      name: tcp1
      nodePort: 7777 #从集群外访问时使用的端口;取值范围通常是30000-32767(取决于您的集群配置)
  selector:
    app: apigateway


        

configMap:


================================查看所有命名空间下的configmap
 kubectl get configmaps -ALL  #正规写法 kubectl get configmaps --all-namespaces


# 获取并以YAML格式输出
kubectl get configmaps -n vcs(命名空间) aems-config(configmap名称) -oyaml

# 描述ConfigMap
kubectl describe configmaps -n vcs aems-config


 



================================指定文件目录 或 单个文件 创建

# 根据config-dir文件夹创建名为test-config的configMap
kubectl create configmap test-config --from-file=../config-dir/

指定单个文件
kubectl create -f yaml-config.yaml
 
================================查看 

# 查看
kubectl get cm yaml-config.yaml -o yaml
 


================================ConfigMap删除
# 根据yaml配置删除
kubectl delete -f yaml-config.yaml
# 根据名字删除
kubectl delete cm literal-config

================================ConfigMap修改
# 在线修改
kubectl edit cm yaml-config

# 离线修改
vim yaml-config.yaml
kubectl apply -f yaml-config.yaml




================================================================
apiVersion: v1
kind: ConfigMap
metadata:
  name: apigateway-cm
  namespace: vcs
data:
  bootstrap.yml: |
    server:
      port: 7777
    logging:
      level:
        com.sdses: debug
    spring:
      application:
        name: gateway-application


============================= Deployment 引用:
  volumes:
  - name: spring-config
	configMap:
	  defaultMode: 420
	  items:
	  - key: bootstrap.yml
		path: bootstrap.yml
	  name: apigateway-cm

==============================================多个key=====================
apiVersion: v1
kind: ConfigMap
metadata:
  name: aems-config
  namespace: vcs
data:
  algo-prod.properties: |
    algo_server.storage.root=/var/www/app/storage
    application.language.supported.0=zh
    application.language.supported.1=en
    message.alarm.days=30
    system.storage.type=1
  application-prod.yml: |
    server:
      port: 7999
    spring:
      datasource:
        druid:
          url: jdbc:mysql://mysql-svc.


volumes:  #物理机器
      - name: edge-volumes
		hostPath:
          path: /dubhe/data/business/
        
      - name: edge-log
	    hostPath:
          path: /dubhe/log/
          type: ""
        
      - name: spring-config
		configMap:
		  name: aems-config
          defaultMode: 420
          items:
          - key: application.yml
            path: application.yml
          - key: application-prod.yml
            path: application-prod.yml
          - key: algo-prod.properties
            path: algo-prod.properties
          - key: bootstrap.yml
            path: bootstrap.yml
          name: aems-config

volumeMounts:  #容器内部
        - mountPath: /var/www/app/storage
          name: edge-volumes
          subPath: ev-edge/storage
        - mountPath: /dubhe/log/vcs
          name: edge-log
          subPath: xxx
        - mountPath: /var/www/app
          name: spring-config
=====================Deployment

[root@master services]# kubectl get deployments -n vcs

NAME               READY   UP-TO-DATE   AVAILABLE   AGE
sss               2/2      1            2           161d
apigateway         2/2     1            2           198d

NAME 列出了集群中 Deployment 的名称。
READY 显示应用程序的可用的 副本 数。显示的模式是“就绪个数/期望个数”。
UP-TO-DATE 显示为了打到期望状态已经更新的副本数。
AVAILABLE 显示应用可供用户使用的副本数。
AGE 显示应用程序运行的时间。

=====================指定deployments  进行扩容操作
kubectl scale deployment sss   --replicas 5


######:为了使HPA正常工作,必须在Pod的资源配置中设置resources.requests.cpu
#当平均CPU使用率超过80%时,HPA将开始增加Pod数量。当CPU使用率低于80%时,HPA将减少Pod数量
kubectl autoscale deployment sss    --min=1 --max=5 --cpu-percent=80 



=====================获取指定空间下的所有的pod
kubectl get deploy -n vcs 或 kubectl get deployments -n vcs  或  kubectl get deployments.apps -n vcs



[root@master services]# kubectl get deploy --show-labels -n vcs

NAME               READY   UP-TO-DATE   AVAILABLE   AGE    LABELS
aems               1/1     1            1           161d   name=aems
apigateway         1/1     1            1           198d   name=apigateway



=============================常用命令
#重新启动指定的Deployment
kubectl rollout restart deployment -n vcs ats-xxx

# 回滚到上一个版本
kubectl rollout undo deployment/ats-xxx

# 查看回滚状态
kubectl rollout status deployment/ats-xxx -n vcs

# 查看历史版本
kubectl rollout history deployment/ats-xxx

# 指定版本查看修订历史的详细信息
kubectl rollout history deployment/ats-xxx -n vcs --revision=164

# 指定版本回滚
kubectl rollout undo deployment/ats-xxx -n vcs --to-revision=164

# 暂定更新
# 暂停滚动更新
kubectl rollout pause deployment/ats-xxx -n vcs

# 恢复滚动更新
kubectl rollout resume deployment/ats-xxx -n vcs

# 查看回滚状态
kubectl rollout status deployment/ats-xxx -n vcs

==============================
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    name: aems
  name: aems
  namespace: vcs
spec:
  progressDeadlineSeconds: 600
  replicas: 1 #设置副本数量为1
  revisionHistoryLimit: 5
  selector:
    matchLabels:
      app: aems
  strategy:
    rollingUpdate:
      maxSurge: 25% #在滚动更新过程中,允许的最大额外Pod数
      maxUnavailable: 25% #在滚动更新过程中,允许的最大不可用Pod数
    type: RollingUpdate #使用滚动更新策略
  template:
    metadata:
      labels:
        app: aems
    spec:
      imagePullSecrets: # 使用Docker镜像拉取密钥
      - name: docker-registry
      serviceAccountName: aems-sa 使用的服务账号名称
      containers:
      - env:
        - name: SPRING_CONFIG
          value: /var/www/app/
        - name: JAVA_OPTS
          value: -Xmx2048M -Xms2048M -XX:MaxMetaspaceSize=512M -XX:MetaspaceSize=256M
            -XX:+CMSParallelRemarkEnabled -XX:+UseConcMarkSweepGC -XX:CMSInitiatingOccupancyFraction=75
            -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=utf-8 -XX:HeapDumpPath=/var/www/app/storage/
            -Dk8s.registry.server=registry-svc.middleware.svc.cluster.local:30443
            -Dk8s.registry.username= -Dk8s.registry.password=
        - name: DEBUG_OPTS
          value: -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005
        image: registry-svc.middleware.svc.cluster.local:30443/service/aems:1.1.0-xx
        imagePullPolicy: Always #总是拉取最新的镜像
        name: aems
		resources:
          limits:
            cpu: "3" #CPU限制
            memory: 3Gi #内存限制
          requests:
            cpu: "2"
            memory: 3Gi
        startupProbe: #启动探针,用于检测容器是否启动成功
          httpGet:
            path: /api/vcs/1.0/-/health
            port: 7999
          initialDelaySeconds: 60 #初始延迟时间
          periodSeconds: 5 #检查间隔时间
          timeoutSeconds: 10 #超时时间
          successThreshold: 1 #成功阈值
          failureThreshold: 10 #失败阈值
        livenessProbe:
          httpGet:
            path: /api/vcs/1.0/-/health
            port: 7999
          initialDelaySeconds: 5
          periodSeconds: 5
          timeoutSeconds: 10
          successThreshold: 1
          failureThreshold: 3
        readinessProbe:
          httpGet:
            path: /api/vcs/1.0/-/ready
            port: 7999
          initialDelaySeconds: 10
          periodSeconds: 5
          timeoutSeconds: 5
          successThreshold: 1
          failureThreshold: 1
        ports:
        - containerPort: 7999
          name: http
          protocol: TCP
        - containerPort: 5005
          name: tcp
          protocol: TCP
        - containerPort: 8000
          name: tcp1
          protocol: TCP
        securityContext:
          capabilities:
            add:
            - IPC_LOCK
          privileged: true
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
        volumeMounts:
        - mountPath: /var/www/app/storage
          name: edge-volumes
          subPath: ev-edge/storage
        - mountPath: /dubhe/log/vcs
          name: edge-log
          subPath: aems
        - mountPath: /var/www/app
          name: spring-config
      restartPolicy: Always #重启策略
      terminationGracePeriodSeconds: 30 #终止宽限期
      volumes:
      - name: edge-volumes
        persistentVolumeClaim:
          claimName: aems-pvc
      - hostPath:
          path: /etc/localtime
          type: ""
        name: localtime
      - hostPath:
          path: /usr/local/ev
          type: ""
        name: as-dir
      - hostPath:
          path: /dubhe/log/
          type: ""
        name: edge-log
      - configMap:
          defaultMode: 420
          items:
          - key: application.yml
            path: application.yml
          - key: application-prod.yml
            path: application-prod.yml
          - key: algo-prod.properties
            path: algo-prod.properties
          - key: bootstrap.yml
            path: bootstrap.yml
          name: aems-config
        name: spring-config

[k8s--数据存储、HostPath、NFS 存储] https://zhuanlan.zhihu.com/p/671032320 

K8S 之 PV、PVC-CSDN博客

PV  、PVC 、NFS------hostPath

PersistentVolume (PV)  [简单理解为一个资源定义]
定义:PV 是集群中的一块存储资源,由管理员配置。它是集群中存储资源的一个抽象,独立于 Pod。
生命周期:PV 的生命周期独立于使用它的 Pod。即使 Pod 被删除,PV 仍然存在,除非被显式删除或回收。
类型:PV 可以基于多种存储类型,如 NFS、iSCSI、Ceph RBD、GlusterFS、AWS EBS 等。
配置:PV 由集群管理员创建和配置,通常通过 YAML 文件定义,并使用 kubectl 命令应用到集群中。
状态:PV 可以有多种状态,如 Available(可用)、Bound(已绑定)、Released(已释放)和 Failed(失败)。



PersistentVolumeClaim (PVC) [从PV 申请的资源]
定义:PVC 是用户对存储资源的请求。它类似于 Pod 对计算资源(如 CPU 和内存)的请求。
生命周期:PVC 的生命周期与使用它的 Pod 相关。当 PVC 被删除时,关联的 PV 可能会被保留、回收或删除,具体取决于 PV 的 reclaimPolicy。
绑定:PVC 会自动与合适的 PV 绑定。如果集群中有多个符合条件的 PV,Kubernetes 会选择一个进行绑定。
配置:PVC 由用户创建,通常通过 YAML 文件定义,并使用 kubectl 命令应用到集群中。
状态:PVC 的状态包括 Pending(等待绑定)、Bound(已绑定)等。



NFS
定义:NFS 是一种网络文件系统协议,允许客户端通过网络访问服务器上的文件系统。在 Kubernetes 中,NFS 可以用作 PV 的后端存储。
用途:NFS 通常用于需要共享存储的场景,允许多个 Pod 同时读写同一个存储卷。
配置:NFS 服务器需要单独设置,然后在 PV 配置中引用 NFS 服务器的 IP 地址和共享目录路径。
优点:
支持多读写访问模式 (ReadWriteMany)。
易于管理和扩展。
适用于需要共享存储的应用场景。
缺点:
性能可能不如本地存储或专用存储解决方案。
依赖于网络连接,网络问题可能影响存储的可用性。



kubectl get pv
kubectl get pvc

===================创建 PV (NFS)==================================

apiVersion: v1
kind: PersistentVolume
metadata:
  name: nfs-pv
spec:
  capacity:
    storage: 10Gi  # 根据需要调整大小
  accessModes:
    - ReadWriteMany  # 支持多读写访问
  nfs:
    server:   # 替换为 NFS 服务器的 IP 地址
    path: /exports/data  # 替换为 NFS 共享目录
  persistentVolumeReclaimPolicy: Retain  # 当 PVC 被删除时保留数据


======================nfs-pvc1.yaml===============================

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc1
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi  # 请求的存储空间大小

=====================nfs-pvc2.yaml================================

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: nfs-pvc2
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1Gi  # 请求的存储空间大小

=====================使用===========================================

apiVersion: v1
kind: Pod
metadata:
  name: test-pod1
spec:
  containers:
  - name: test-container1
    image: nginx
    volumeMounts:
    - mountPath: /mnt/data
      name: nfs-storage1
  volumes:
  - name: nfs-storage1
    persistentVolumeClaim:
      claimName: nfs-pvc1



==========================================================================

        volumeMounts:
        - mountPath: /var/www/app/storage
          name: edge-volumes
          subPath: ev-edge/storage
        - mountPath: /etc/localtime
          name: localtime
        - mountPath: /usr/local/ev
          name: as-dir
        - mountPath: /dubhe/log/vcs
          name: edge-log
          subPath: aems
        - mountPath: /var/www/app
          name: spring-config
      restartPolicy: Always
      terminationGracePeriodSeconds: 30
      volumes:
      - name: edge-volumes
        persistentVolumeClaim:
          claimName: aems-pvc
      - hostPath:
          path: /etc/localtime
          type: ""
        name: localtime
      - hostPath:
          path: /usr/local/ev
          type: ""
        name: as-dir
      - hostPath:
          path: /dubhe/log/
          type: ""
        name: edge-log
      - configMap:
          defaultMode: 420
          items:
          - key: application.yml
            path: application.yml
          - key: application-prod.yml
            path: application-prod.yml
          - key: algo-prod.properties
            path: algo-prod.properties
          - key: bootstrap.yml
            path: bootstrap.yml
          name: aems-config
        name: spring-config


hostPath 的 type 字段选项

"" (空字符串): 默认值,等同于 DirectoryOrCreate。
Directory: 指定路径必须存在,并且是一个目录。
DirectoryOrCreate: 如果路径不存在,则创建一个空目录;如果路径存在,则必须是一个目录。
File: 指定路径必须存在,并且是一个常规文件。
FileOrCreate: 如果路径不存在,则创建一个空文件;如果路径存在,则必须是一个常规文件。
Socket: 指定路径必须存在,并且是一个 Unix 域套接字。
CharDevice: 指定路径必须存在,并且是一个字符设备。
BlockDevice: 指定路径必须存在,并且是一个块设备。
# 无头服务   clusterIP: None 【无头服务通常与StatefulSet一起使用,这样每个Pod可以获得一个固定的、可预测的DNS名称,有助于集群成员发现】


命名规则:-..svc.
示例:rabbitmq-headless-0.middleware.svc.cluster.local 和 rabbitmq-headless-1.middleware.svc.cluster.local



apiVersion: v1            #定义一个NodePort类型的svc,用于外部访问
kind: Service
metadata:
  name: nacos-svc
  namespace: middleware
  labels:
    app: nacos
spec:
  ports:
    - port: 8848
      name: server
      targetPort: 8848
      nodePort: 8848
    - port: 9848
      name: server-grpc
      targetPort: 9848
      nodePort: 9848
  type: NodePort
  selector:
    app: nacos
---
apiVersion: v1
kind: Service         #定义一个无头svc,供xx使用
metadata:
  name: nacos-headless
  namespace: middleware
  labels:
    app: nacos
spec:
  publishNotReadyAddresses: true
  ports:
    - port: 8848
      name: server
      targetPort: 8848
    - port: 9848
      name: server-grpc
      targetPort: 9848

  clusterIP: None
  selector:
    app: nacos




=========================================================================
从集群内部访问
当你的应用程序运行在Kubernetes集群内部时,它们可以通过以下方式访问RabbitMQ节点:

使用DNS解析:
应用程序可以通过DNS名称 rabbitmq-headless.middleware.svc.cluster.local 解析到所有带有 app: rabbitmq 标签的Pod。
DNS会返回一个A记录列表,每个记录对应一个Pod的IP地址。

直接连接到Pod:
如果你需要连接到特定的Pod,可以使用 rabbitmq-headless-.middleware.svc.cluster.local 的格式,其中  是Pod的索引号(例如 rabbitmq-headless-0.middleware.svc.cluster.local)。

使用标准的AMQP客户端库:
应用程序可以使用标准的AMQP客户端库(如Pika for Python, RabbitMQ .NET Client, etc.)连接到5672端口。
连接字符串可以是 amqp://:5672 或 amqp://rabbitmq-headless.middleware.svc.cluster.local:5672


================================================================

kind: Secret
apiVersion: v1
metadata:
  name: rabbitmq-secret
  namespace: middleware
stringData:
  pass: xxxx
  user: xxxx
type: Opaque
---
apiVersion: v1
kind: Service
metadata:
  name: rabbitmq-management
  namespace: middleware
  labels:
    app: rabbitmq
spec:
  ports:
  - port: 15672
    name: http
    nodePort: 15672
  - port: 5672
    name: amqp
    nodePort: 5672
  selector:
    app: rabbitmq
  type: NodePort     # 外界可以访问
---
apiVersion: v1
kind: Service
metadata:
  name: rabbitmq-headless
  namespace: middleware
  labels:
    app: rabbitmq
spec:
  ports:
  - port: 5672
    name: amqp
  - port: 4369
    name: epmd
  - port: 25672
    name: rabbitmq-dist
  clusterIP: None      # 无头service,外界不可以访问,只能由pod内部访问
  selector:
    app: rabbitmq

你可能感兴趣的:(kubernetes,学习,容器)