I'm attempting to connect to my MongoDB pod, but I'm failing. Previously, I was just using an online resource to host my MongoDB. Now I want to deploy my DB with Kubernetes. However, I'm having issues connecting to my DB pod via my Flask application and cannot find any examples that are using Minikube or python.
This is how I'm attempting to connect to my pod and populate it:
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."
This is my deployment:
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
I have tried:
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
as suggested, but I get the error pymongo.errors.OperationFailure: Authentication failed.
when trying to add to my db via /populate_db
I've also tried:
mongo = MongoClient("mongodb://mongo:27017/patients")
with the same outcome as the latter.
Edit:
There was a problem with my docker image not updating correctly
mongo = MongoClient("mongodb://mongo:27017/patients")
works fine.
url = 'http://{}:{}/rba-db'.format(be_host, be_port)
http://
is that right?
app.config["MONGO_URI"] = "mongodb://localhost:27017/myDatabase"
As far as I know, mongo url = "mongodb://localhost:27017/myDatabase"