Skip to content

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.

Create a dedicated namespace:

Terminal window
kubectl create namespace mongo

Deploy the database, its storage, and a Service into the namespace:

Terminal window
cat <<'EOF' | kubectl apply -f -
apiVersion: v1
kind: Secret
metadata:
name: mongo
namespace: mongo
stringData:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: change-me
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongo
namespace: mongo
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: mongo
namespace: mongo
spec:
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: v1
kind: Service
metadata:
name: mongo
namespace: mongo
spec:
selector:
app: mongo
ports:
- port: 27017
targetPort: 27017
EOF

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:27017 over a public endpoint. It tunnels through the API server and exposes nothing.
  • To expose it for real, enable MongoDB’s own TLS (--tlsMode requireTLS with 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.

Check it’s responding (use the password you set above):

Terminal window
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:

Terminal window
kubectl exec -n mongo -it deploy/mongo -- mongosh -u root -p change-me

From 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=admin

Delete the namespace to remove everything at once:

Terminal window
kubectl delete namespace mongo

This destroys the database’s data along with it.