我是docker和kubernetes的初学者。我在kubernetes集群上的pod内运行了docker容器,我正在尝试连接到mongo db,但它一直失败
当我检查 pod 和服务时,一切运行良好:

NAME                               READY   STATUS    RESTARTS   AGE

auth-depl-65565b6884-rxcvj         1/1     Running   0          58s

auth-mongo-depl-6c87496969-9sxj4   1/1     Running   0          56s


NAME             TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)     AGE

auth-mongo-srv   ClusterIP   10.106.91.10    <none>        27017/TCP   2m

auth-srv         ClusterIP   10.96.108.116   <none>        3000/TCP    2m3s

kubernetes       ClusterIP   10.96.0.1       <none>        443/TCP     2m20s




我的Mongo部署文件:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-mongo-depl
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongo-depl
  template:
    metadata:
      labels:
        app: mongo-depl
    spec:
      containers:
        - name: mongo-depl
          image: mongo
---
apiVersion: v1
kind: Service
metadata:
  name: auth-mongo-srv
spec:
  selector:
    type: ClusterIP
    app: mongo-depl
  ports:
    - name: db
      protocol: TCP
      port: 27017
      targetPort: 27017

与数据库的连接:
const start = async (): Promise<void> => {
  try {
    await mongoose.connect("mongodb://auth-mongo-srv:27017/auth", {
      useCreateIndex: true,
      useFindAndModify: false,
      useNewUrlParser: true,
      useUnifiedTopology: true
    });
    console.log("connected to db");
  } catch (error) {
    console.log(error);
  }
};

start();
当我检查日志时,出现以下错误:
[auth] MongooseServerSelectionError: connect ECONNREFUSED 10.106.91.10:27017
 reason: TopologyDescription {
   type: 'Single',
   setName: null,
   maxSetVersion: null,
   maxElectionId: null,
   servers: Map(1) { 'auth-mongo-srv:27017' => [ServerDescription] },
   stale: false,
   compatible: true,
   compatibilityError: null,
   logicalSessionTimeoutMinutes: null,
   heartbeatFrequencyMS: 10000,
   localThresholdMS: 15,
   commonWireVersion: null
 }
任何线索可能导致问题的原因?

最佳答案

您似乎未正确配置服务的选择器。您添加了标签type: ClusterIP,因此该服务未选择您的mongo pod,因为它们没有这样的标签。您可能想在type: ClusterIP下添加spec,而不是selector。因此,请从选择器中删除标签type: ClusterIP,并选择将其放在spec下(ClusterIP类型是服务的默认类型)。

关于mongodb - 在kubernetes集群中运行的ECONNREFUSED MongoDB,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/63896990/

10-11 06:43