无法通过Flask应用程序Pod连接到MongoDB Pod

时间:2019-01-30 03:28:36

标签: python flask kubernetes

我正在尝试连接到我的MongoDB pod,但是失败了。以前,我只是使用在线资源来托管我的MongoDB。现在,我想用Kubernetes部署数据库。但是,我在通过Flask应用程序连接到数据库Pod时遇到问题,找不到使用Minikube或python的任何示例。

这是我尝试连接到吊舱并填充它的方式:

be_host = os.getenv('MONGO-DB_SERVICE_HOST', 'mongo-db')
be_port = os.getenv('MONGO-DB_SERVICE_PORT', '27017')
url = 'http://{}:{}/rba-db'.format(be_host, be_port)

app.config['MONGO_DBNAME'] = 'pymongo_db'
app.config['MONGO_URI'] = url

mongo = PyMongo(app)

@app.route('/populate_db')
def populate_db():
    patient = mongo.db.patients
    patient.insert({'id': 1, 'fname': 'Jill', 'lname': 'Smith', 'age': '50', 'weight': '63.3', 'conditions': ['Stage 2 Diabetes', 'Cancer', 'Aids']})
    patient.insert({'id': 2, 'fname': 'John', 'lname': 'Smith', 'age': '52', 'weight': '86.2', 'conditions': ['Heart Disease', 'Cancer']})
    patient.insert({'id': 3, 'fname': 'Ryan', 'lname': 'Gosling', 'age': '25', 'weight': '75', 'conditions': ['Flu']})
    patient.insert({'id': 4, 'fname': 'Sean', 'lname': 'Winnot', 'age': '21', 'weight': '82', 'conditions': ['Lupis']})
    return "Patients Added."

这是我的部署:

kind: Service
apiVersion: v1
metadata:
  name: mongo-db
spec:
  type: NodePort
  selector:
    app: mongo-db
  ports:
  - protocol: TCP
    nodePort: 31003
    port: 27017
    targetPort: 27017
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mongo-db
  labels:
    app: mongo-db
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mongo-db
  template:
    metadata:
      labels:
        app: mongo-db
    spec:
      containers:
      - name: mongo-db
        image: mongo:latest
        ports:
        - containerPort: 27017

我尝试过:

app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"

按照建议,但是尝试通过/ populate_db添加到我的数据库时出现错误pymongo.errors.OperationFailure: Authentication failed.

我也尝试过:

mongo = MongoClient("mongodb://mongo:27017/patients")

与后者的结果相同。

编辑:

我的docker映像存在问题,无法正确更新

mongo = MongoClient("mongodb://mongo:27017/patients")

工作正常。

1 个答案:

答案 0 :(得分:0)

url = 'http://{}:{}/rba-db'.format(be_host, be_port)

http://是吗?

app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"

据我所知mongo url = "mongodb://localhost:27017/myDatabase"

相关问题