将应用程序部署与 K8s 上的数据库服务连接起来

Connect app deployment with database service on K8s

我必须将我的应用程序部署与 PostgresDB 部署连接起来。 目前,我将 Postgres 集群 IP 放在我的应用程序环境中,如下所示:

apiVersion: apps/v1
kind: Deployment
.......
containers:
  - name: "#{tenant}#-app-widget"
    image: baserepository:#{app_image_version}#
    ports:
      - containerPort: 8080
    env:
      - name: NODE_ENV
        value: "#{NODE_ENV}#"
      - name: AUTH_CALLBACK_URL
        value: "https://base.#{DNSSubdomain}#/auth/callback"
      - name: DB_HOST
        value: "10.0.196.195"
      - name: DB_PORT
        value: "5432"
      - name: DB_DATABASE
        value: "#{DB_DATABASE}#"

我想做的是在 DB_HOST 的值中放入对 postgres 服务的引用,以便在部署我的应用程序时更加动态。 这是我为 postgres 部署和服务所做的工作:

apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: "#{tenant}#-postgres"
  name: "#{tenant}#-postgres"
  labels:
    app: "#{tenant}#-postgres"
    product: "#{tenant}#-postgres"
    app.kubernetes.io/name: "#{tenant}#-postgres"
    app.kubernetes.io/version: "10.4"
    app.kubernetes.io/managed-by: "#{managed_by}#"
    app.kubernetes.io/component: "#{tenant}#-postgres"
    app.kubernetes.io/part-of: "#{tenant}#-postgres"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: "#{tenant}#-postgres"
  template:
    metadata:
      labels:
        app: "#{tenant}#-postgres"
    spec:
      containers:
        - name: "#{tenant}#-postgres"
          image: postgres:10.4
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: "#{tenant}#-postgres-config"
          resources:
            requests:
              memory: "#{POSTGRES_RESOURCES_REQUESTS_MEMORY}#"
              cpu: "#{POSTGRES_RESOURCES_REQUESTS_CPU}#"
            limits:
              memory: "#{POSTGRES_RESOURCES_LIMITS_MEMORY}#"
              cpu: "#{POSTGRES_RESOURCES_LIMITS_CPU}#"
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: "#{tenant}#-postgredb"
      volumes:
        - name: "#{tenant}#-postgredb"
          persistentVolumeClaim:
            claimName: "#{tenant}#-postgres-pv-claim"
      affinity:
        nodeAffinity:
          preferredDuringSchedulingIgnoredDuringExecution:
            - weight: 1
              preference:
                matchExpressions:
                  - key: tier
                    operator: In
                    values:
                      - "#{POSTGRES_AFFINITY_PREFERRED_VALUE}#"
---
apiVersion: v1
kind: Service
metadata:
  namespace: "#{tenant}#-postgres"
  name: "#{tenant}#-postgres"
  labels:
    app: "#{tenant}#-postgres"
spec:
  type: NodePort
  ports:
    - port: 5432
  selector:
    app: "#{tenant}#-postgres"

能否举例说明如何执行此操作? 我认为不需要入口,因为我必须关联同一集群内的两个部署。 非常感谢你, 戴夫

我找到了解决方案,您必须将服务元数据 {name}.{namespace} 的 DB_HOST 值放入。这足以将应用程序部署与 Postgres 实例进行动态通信。 DB_HOST 将是“#{tenant}#-postgres。#{tenant}#-postgres”