This sidecar detects the current MongoDB replica set primary and labels Kubernetes pods so services can target the writable node.
Every 5 seconds the sidecar:
- Connects to MongoDB (
MONGO_ADDRESS, defaultlocalhost:27017). - Detects the primary pod name.
- Lists pods in
NAMESPACEmatchingLABEL_SELECTOR. - Patches labels:
- primary pod:
primary=true - other pods:
primary=falsewhenLABEL_ALL=true - other pods: removes
primarylabel whenLABEL_ALL=false
- primary pod:
It uses Kubernetes Patch (strategic merge), not full-object Update.
apiVersion: v1
kind: Service
metadata:
name: mongo-external
spec:
type: LoadBalancer
ports:
- name: mongo
port: 27017
selector:
role: mongo
primary: "true"When running inside Kubernetes, in-cluster config is used automatically.
When running outside a cluster, kubeconfig defaults to ~/.kube/config and can be overridden with --kubeconfig.
Environment variables:
| Variable | Required | Default | Description |
|---|---|---|---|
LABEL_SELECTOR |
yes | none | Pod label selector (for example role=mongo). |
NAMESPACE |
no | default |
Namespace where pods are listed and patched. |
MONGO_ADDRESS |
no | localhost:27017 |
MongoDB endpoint used for primary detection. |
LABEL_ALL |
no | false |
Boolean. If true, non-primary pods get primary=false; if false, the label is removed. |
DEBUG |
no | false |
Boolean. If true, enables debug logging. |
LABEL_ALL and DEBUG are parsed as booleans. Invalid values fail startup.
Container images are published to GHCR at:
ghcr.io/combor/k8s-mongo-labeler-sidecar
docker pull ghcr.io/combor/k8s-mongo-labeler-sidecar:latest-amd64
docker pull ghcr.io/combor/k8s-mongo-labeler-sidecar:latest-arm64deployment-example.yaml can be used as an example deployment manifest.
The repository includes an end-to-end test environment in test/integration.
Prerequisites:
kindkubectl- Docker with BuildKit/Buildx enabled
Run:
./test/integration/run.shOptional overrides:
NAMESPACE(defaultmongo-it)CLUSTER_NAME(defaultmongo-labeler-it)LABELER_IMAGE(defaultmongo-labeler-it:local)TIMEOUT(default240s)KEEP_CLUSTER=true(keep cluster for debugging)
The script creates a temporary kind cluster, deploys Mongo + sidecar, and verifies that mongo-0 receives primary=true.