1 / 1
Apr 2024

The kubernetes (k8s) is woking perfectly without replicaset, but once I am using mongodb replicaset, then the authentication is not woking, but if i remove the authentication env values then the replicaset is working. Mongodb requires replicaset for using transaction feature. here is the yml conf, can you please have a look kindly?

I am using custom Docker file upload into the docker hub. The docker file is also included.

Docker file for mongodb for generating mongo-keyfile

FROM mongo
RUN openssl rand -base64 756 > /etc/mongo-keyfile
RUN chmod 400 /etc/mongo-keyfile
RUN chown mongodb:mongodb /etc/mongo-keyfile

Kubernetes Service

apiVersion: v1
kind: Service
metadata:
name: mdb
labels:
app: mdb
spec:
ports:

  • port: 27017
    targetPort: 27017
    name: mdb
    clusterIP: None
    selector:
    app: mdb

Kubernetes Statefulset Mongodb

apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mdb
spec:
selector:
matchLabels:
app: mdb # has to match .spec.template.metadata.labels
serviceName: “mdb”
replicas: 1
minReadySeconds: 10 # by default is 0
template:
metadata:
labels:
app: mdb # has to match .spec.selector.matchLabels
spec:
terminationGracePeriodSeconds: 10
containers:
- name: mdb
image: shourovroy/motonok-dbs:latest
command: [“mongod”]
args: [“–auth”, “–replSet”, “rs0”, “–keyFile”, “/etc/mongo-keyfile”, “–bind_ip_all”, “–port”, “27017”]
env:
- name: MONGO_INITDB_ROOT_USERNAME
value: admin
- name: MONGO_INITDB_ROOT_PASSWORD
value: admin
ports:
- containerPort: 27017
volumeMounts:
- name: mdb-vol
mountPath: /data/db
volumeClaimTemplates:

  • metadata:
    name: mdb-vol
    spec:
    accessModes: [ “ReadWriteOnce” ]
    resources:
    requests:
    storage: 1Gi

To rs.initiate the replicaset in mongodb access the pod

kubectl exec -it mdb-0 – mongosh

rs.initiate conf
rs.initiate((
{
_id: “rs0”,
version: 1,
members: [
{ _id: 0, host : “127.0.0.1:27017” } # using mdb-0.mdb.default.cluster.local not working. 127.0.0.1 is working.
]
}
))

Exposing the pod to external access

kubectl expose pod mdb-0 --port 27017 --target-port 27017 --type LoadBalancer

everything works fine without authentication. I wan to authenticate the database.
If I commented the env part then working good. but using env for setup username and password its not working showing authentication failed.