Run MongoDB
This assumes you can already reach your cluster with kubectl (see the
kubectl quickstart).
You’ll deploy a single MongoDB instance in its own namespace, backed by persistent storage so its data survives pod restarts. The cluster’s default StorageClass provisions the volume for you.
Deploy
Section titled “Deploy”Create a dedicated namespace:
kubectl create namespace mongoDeploy the database, its storage, and a Service into the namespace:
cat <<'EOF' | kubectl apply -f -apiVersion: v1kind: Secretmetadata: name: mongo namespace: mongostringData: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: change-me---apiVersion: v1kind: PersistentVolumeClaimmetadata: name: mongo namespace: mongospec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi---apiVersion: apps/v1kind: Deploymentmetadata: name: mongo namespace: mongospec: replicas: 1 strategy: type: Recreate selector: matchLabels: app: mongo template: metadata: labels: app: mongo spec: containers: - name: mongo image: mongo:8 envFrom: - secretRef: name: mongo ports: - containerPort: 27017 volumeMounts: - name: data mountPath: /data/db volumes: - name: data persistentVolumeClaim: claimName: mongo---apiVersion: v1kind: Servicemetadata: name: mongo namespace: mongospec: selector: app: mongo ports: - port: 27017 targetPort: 27017EOFSecurity
Section titled “Security”This Service is ClusterIP, so the database is only reachable from inside the
cluster. On a single-tenant skube cluster that’s the safe default: keep your app
and database in the cluster and connect over the Service with no TLS.
If you need to reach it from outside the cluster:
- For occasional access, prefer
kubectl port-forward -n mongo service/mongo 27017:27017over a public endpoint. It tunnels through the API server and exposes nothing. - To expose it for real, enable MongoDB’s own TLS (
--tlsMode requireTLSwith a cert and key). The Ingress and Gateway guides are HTTP-only and don’t apply to the MongoDB wire protocol. - Use a strong password, not
change-me, and rotate the secret if it leaks.
Connect
Section titled “Connect”Check it’s responding (use the password you set above):
kubectl exec -n mongo deploy/mongo -- mongosh -u root -p change-me --quiet --eval "db.runCommand({ ping: 1 })"A { ok: 1 } response means it’s up. Open an interactive shell:
kubectl exec -n mongo -it deploy/mongo -- mongosh -u root -p change-meFrom there, show dbs lists databases.
Other workloads in the cluster connect with this URI (<password> is the value
from the secret above):
mongodb://root:<password>@mongo.mongo.svc.cluster.local:27017/?authSource=adminClean up
Section titled “Clean up”Delete the namespace to remove everything at once:
kubectl delete namespace mongoThis destroys the database’s data along with it.