MongoDB
Kubernetes
Authentication
Database Security
Cloud Deployment

Authentication mongo deployed on kubernetes

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Running MongoDB on Kubernetes without authentication is fine only for throwaway local experiments. In any real environment, you should create credentials, store them as Kubernetes secrets, and start MongoDB with authentication enabled. The practical setup usually involves one secret, one workload manifest, persistent storage, and a connection string that points clients at the correct authentication database.

Store Credentials in a Secret

The first step is to avoid hardcoding usernames and passwords in manifests. Put them in a Kubernetes Secret.

yaml
1apiVersion: v1
2kind: Secret
3metadata:
4  name: mongo-auth
5  namespace: data
6type: Opaque
7stringData:
8  MONGO_INITDB_ROOT_USERNAME: admin
9  MONGO_INITDB_ROOT_PASSWORD: supersecret

Apply it:

bash
kubectl apply -f mongo-secret.yaml

This gives the workload a safe place to read credentials from at startup.

Start MongoDB With Auth-Initializing Environment Variables

The official MongoDB container image supports MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD during initialization. A simple single-instance deployment looks like this:

yaml
1apiVersion: apps/v1
2kind: Deployment
3metadata:
4  name: mongo
5  namespace: data
6spec:
7  replicas: 1
8  selector:
9    matchLabels:
10      app: mongo
11  template:
12    metadata:
13      labels:
14        app: mongo
15    spec:
16      containers:
17        - name: mongo
18          image: mongo:7
19          ports:
20            - containerPort: 27017
21          envFrom:
22            - secretRef:
23                name: mongo-auth
24          volumeMounts:
25            - name: mongo-data
26              mountPath: /data/db
27      volumes:
28        - name: mongo-data
29          persistentVolumeClaim:
30            claimName: mongo-pvc

And the matching PVC:

yaml
1apiVersion: v1
2kind: PersistentVolumeClaim
3metadata:
4  name: mongo-pvc
5  namespace: data
6spec:
7  accessModes:
8    - ReadWriteOnce
9  resources:
10    requests:
11      storage: 10Gi

The root user is created when the database initializes against an empty data directory.

Expose MongoDB Internally

Most applications on Kubernetes should access MongoDB through a ClusterIP service.

yaml
1apiVersion: v1
2kind: Service
3metadata:
4  name: mongo
5  namespace: data
6spec:
7  selector:
8    app: mongo
9  ports:
10    - port: 27017
11      targetPort: 27017

Pods in the same namespace can then use mongo:27017 as the host name.

Connect With the Right Authentication Database

When you initialize the root user through the standard environment variables, that account is typically stored in the admin database. Client applications therefore need the right auth source in the connection string.

text
mongodb://admin:supersecret@mongo:27017/appdb?authSource=admin

If you omit authSource=admin, login may fail even though the credentials are correct.

That one detail causes a large percentage of "authentication failed" reports in containerized Mongo setups.

Initialization Happens Only Once Per Data Directory

The root-user environment variables are used during initialization of a fresh database directory. If you already have persistent data and change the secret later, MongoDB does not recreate the root user automatically.

That means you should think carefully about first boot versus ongoing credential rotation. A secret update alone is not a full user-management strategy for an already initialized database.

For more advanced setups, create application users explicitly using init scripts or admin commands rather than relying on the root account for application traffic.

Debugging Authentication Problems

A practical debugging checklist is:

  • confirm the secret values were actually mounted into the pod
  • confirm MongoDB initialized against an empty data directory the first time
  • check that the client uses the right host, username, password, and authSource
  • inspect logs for startup and authentication failures

Useful commands:

bash
kubectl logs deployment/mongo -n data
kubectl exec -it deployment/mongo -n data -- mongosh -u admin -p supersecret --authenticationDatabase admin

This helps separate credential problems from networking or storage problems.

Common Pitfalls

The most common mistake is assuming that updating the Kubernetes secret will recreate the Mongo root user on an already initialized persistent volume. It will not.

Another issue is forgetting authSource=admin for root credentials created by the initialization variables.

Developers also often run the application against the root user permanently. That works, but it is not good long-term security hygiene. Create app-specific users for application access.

Finally, do not skip persistent storage. Without it, the pod may restart into a fresh database and reinitialize in ways that surprise the application.

Summary

  • Store Mongo credentials in a Kubernetes secret, not directly in manifests.
  • Use the Mongo initialization environment variables on first boot to create the root user.
  • Back MongoDB with persistent storage so auth setup is stable across restarts.
  • Use a connection string with the correct authSource, often admin for the root user.
  • Treat secret updates and user lifecycle as separate concerns once the database has been initialized.

Course illustration
Course illustration

All Rights Reserved.