I'm trying to create username/password for my mongodb on kubernetes. But seems MONGO_INITDB_ROOT_USERNAME/PASSWORD is not work or work incorrect as I cannot login with this credentials:
apiVersion: apps/v1beta1
kind: StatefulSet
metadata:
name: mongotest
spec:
revisionHistoryLimit: 3
selector:
matchLabels:
app: mongotest
replicas: 1
podManagementPolicy: Parallel
updateStrategy:
type: RollingUpdate
template:
metadata:
labels:
app: mongotest
spec:
hostname: mongotest
containers:
- name: mongotest
image: mongo
imagePullPolicy: Always
restartPolicy: Always
env:
- name: "MONGO_DATA_DIR"
value: "/data/db"
- name: "MONGO_LOG_DIR"
value: "/data/logs"
- name: MONGO_INITDB_ROOT_USERNAME
value: test
- name: MONGO_INITDB_ROOT_PASSWORD
value: test
- name: MONGO_INITDB_DATABASE
value: admin
lifecycle:
postStart:
exec:
command:
- /bin/sh
- -c
- >
mongo --eval 'db.auth('test', 'test');db = db.getSiblingDB("admin"); db.createUser({ user: "admin", pwd: "test", roles: [{ role: "root", db: "admin" }]});'
ports:
- name: port27017
containerPort: 27017
Gathering all the information from the comments: The reason why the authentication was failing was due to unrecognized username/password. Removing lifecycle section works as it disables authentication and the user is able to reach the MongoDB and create new users.
Following MongoDB documentation:
So in case of docker you could run something like:
docker run -d --name some-mongo -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo
In Kubernetes as it has different character so you could either make containers to run specific commands in the configuration yaml: for example:
containers: - image: mongo name: mongoadmin command: ["mongo", "--auth"]
Although the safest way is to use secrets, because passing username and password in environment variables is not the best practice. You can find more about secrets in the official documentation. And more from Docker perspective in Docker Secrets chapter here.