首页 > 解决方案 > 无法从 kubernetes 集群连接到 mongodb atlas 集群

问题描述

大家好,我无法从我的 kubernetes 集群连接到 mongo atlas 数据库作为 kubernetes 集群外部的服务。

这是我遵循的步骤。

在我的 nodejs 代码中使用 dbUri= 'mongodb://username:password' + process.env.MONGO_URL +'/database-name'

这是集群 ip 服务配置

kind: Service
apiVersion: v1
metadata:
  name: mongo-cluster-ip-service
spec:
  type: ClusterIP
  ports:
  - port: 27017
    targetPort: 27017

然后我有相同服务的端点

kind: Endpoints
apiVersion: v1
metadata:
  name: mongo-cluster-ip-service
subsets:
  - addresses:
    - ip: 35.187.27.116
    ports:
    - port: 27017
  - addresses:
    - ip: 35.241.213.79
    ports:
    - port: 27017
  - addresses:
    - ip: 104.155.120.154
    ports:
    - port: 27017

然后我有我的部署,它想通过一个 env 变量将它用于 Pod

apiVersion: apps/v1
kind: Deployment
metadata:
  name: user-reg-auth-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: user-reg-auth
  template:
    metadata:
      labels:
        app: user-reg-auth
    spec:
      imagePullSecrets:
        - name: ofinowregcred # this is a manually applied secret to the cluster using kubectl create secret
      containers:
      - name: user-reg-auth
        image: ofinow/user-reg-auth
        ports:
        - containerPort: 8080
        # resources:
        #   requests:
        #     memory: "64Mi"
        #     cpu: "250m"
        #   limits:
        #     memory: "128Mi"
        #     cpu: "500m"
        env:
          - name: MONGO_URL
            value: mongo-cluster-ip-service

现在的问题是 mongo-cluster-ip-service 没有得到解决,所以我无法连接。我请求帮助

我遵循了谷歌最佳实践指南 https://cloud.google.com/blog/products/gcp/kubernetes-best-practices-mapping-external-services

标签: mongodbkubernetesminikubemongodb-cluster

解决方案


尝试其中任何一个;

溶液A

  1. 将 Kubernetes 集群的端点加入 MongoDB 网络访问 IP 白名单。

  2. 在您的 k8s pod(或部署)清单的 pod 规范下,添加一个dnsPolicy字段,其值设置为Default。因此,您的 Pod(基本上是您的容器)将通过主节点的名称解析配置连接到 mongo。

溶液 B

  1. 将您的 k8s 集群中的所有节点端点添加到 MongoDB 网络访问 IP 白名单。

  2. 在您的 k8s pod(或部署)清单的 pod 规范下,添加一个dnsPolicy字段,其值设置为ClusterFirstWithHostNet。由于 pod 与您的主机网络一起运行,因此它们可以访问在 localhost 上侦听的服务。


推荐阅读