如何(正确)在 Kubernetes 上部署 MongoDB 并从另一个 Pod/作业访问它?

Phi*_*aro 3 python mongodb kubernetes

1. 问题描述

我试图运行MongoDB Deployment+ServiceKubernetes,而其他Pods/JobsContainers可以访问它。到目前为止,我显然已经成功地部署了它,但是每当我尝试从Job,Pod或 中访问它时Container,我都会得到(请注意,我正在使用0.0.0.0而不是localhost为了访问主机;并且我的超时为 30 秒):

pymongo.errors.ServerSelectionTimeoutError: 0.0.0.0:30001: [Errno 111] Connection refused
Run Code Online (Sandbox Code Playgroud)

2.在本地,它似乎工作......

如果我尝试通过访问它Python CLI,它确实看起来像它的工作原理,但:

>>> import pymongo
>>> client = pymongo.MongoClient(host='0.0.0.0', port=30001) # 'localhost' also works
>>> client.list_database_names()
['admin', 'config', 'local', 'test_db'] # 'test_db' is a db I had previously created
Run Code Online (Sandbox Code Playgroud)

尝试访问时是否应该使用另一个主机地址MongoDB service?(如果是这样,它显示在kubectl describe svc <service_name>哪里?)

3.DeploymentService配置

我的MongoDB deployment(改编自Nigel Poulton 的 Kubernetes Book)是:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mymongodb-dep
spec:
  replicas: 1
  selector:
    matchLabels:
      app: hello-mongo
  minReadySeconds: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: hello-mongo
    spec:
      containers:
      - name: mongo
        image: mongo
        imagePullPolicy: IfNotPresent
        ports:
            - containerPort: 27017
Run Code Online (Sandbox Code Playgroud)

service是:

apiVersion: v1
kind: Service
metadata:
  name: hello-svc
  labels:
    app: hello-mongo
spec:
  type: NodePort
  ports:
  - port: 27017
    nodePort: 30001
    protocol: TCP
  selector:
    app: hello-mongo
Run Code Online (Sandbox Code Playgroud)

Bel*_*ter 5

您在Kubernetes集群内部和外部的连接体验会有所不同。

在集群内,您应该引用MongoDB Podusing<service-name>.<namespace-name>.svc.cluster.local而不是0.0.0.0。所以,在你的情况下,最终host会是hello-svc.default.svc.cluster.local.

另请注意,port应该将 引用为在集群内看到的那个NodePort,而不是用于从外部访问集群的 。在您的情况下,那将是27017.