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
spec:
selector:
role: mongo
primary: "true"
ports:
- name: mongo
port: 27017When 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. |
K8S_REQUEST_TIMEOUT |
no | 10s |
Timeout for Kubernetes list/patch API requests (Go duration format, for example 5s, 1m). |
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. K8S_REQUEST_TIMEOUT is parsed as a Go duration. 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:0.6.2deployment-example.yaml can be used as an example deployment manifest.
Note: the example runs MongoDB without authentication or TLS and is intended for demonstration only. The bundled
NetworkPolicylimits access to port 27017 to pods in the same namespace, but it is only enforced by CNIs that implement NetworkPolicy. Before production use, enable MongoDB authentication (keyFile/SCRAM) and TLS, and review the resource limits and security contexts.
The repository includes an end-to-end test environment in test/integration.
Prerequisites:
Run:
./test/integration/run.shOptional overrides:
CLUSTER_NAME(defaultkind-mongo-labeler)LABELER_IMAGE(defaultmongo-labeler:local)USE_PREBUILT_IMAGE(defaultfalse) — skip building and use an existing imageTIMEOUT(default240s)KEEP_CLUSTER=true(keep cluster for debugging)
The script creates a temporary kind cluster, deploys a 3-pod Mongo StatefulSet and verifies that exactly one pod has primary=true while non-primary pods have primary=false. It also verifies that the mongo Service routes to the primary pod via EndpointSlice.
The repository uses a single workflow for GitHub and local runs: .github/workflows/ci-release.yml.
Prerequisites:
Run the full workflow locally:
act -W .github/workflows/ci-release.yml