Kubernetes uses the IP-per-pod model. If I understand correctly, you want to create three mongo pods, and write IP addresses of the three pods in /etc/hosts
of each container. Modifying the /etc/host
files directly might not be a good idea for many reasons (e.g., the pod may die and be replaced).
For peer discovery in kubernetes, you need to
- Find out the IP addresses of the peers.
- Update your application with the addresses.
(1) is achievable using Headless Service. (2) requires your to write a sidecar container to run along side with your mongo containers, performs (1), and configures your application. The sidecar container is highly application-specific and you may want to read some related stackoverflow questions about doing this for mongodb.
As for (1), you can create a Headless Service by using this service.yaml with the clusterIP set to None.
spec:
clusterIP: None
Then, you can create a replication controller which creates the desired number of mongo pods. For example, you can use mongo-controller.yaml, replaces the gcePersistentDisk
with a desired local disk volume type (e.g. emptyDir
or hostPath
), and change the replica number to 3.
Each of the mongo pod will be assigned an IP address automatically, and is labeled with name=mongo
. The headless service uses a label selector to find the pods. When querying DNS with the service name from a node or a container, it will return a list of IP addresses of the mongo pods.
E.g.,
$ host mongo
mongo.default.svc.cluster.local has address 10.245.0.137
mongo.default.svc.cluster.local has address 10.245.3.80
mongo.default.svc.cluster.local has address 10.245.1.128
You can get the addresses in the sidecar container you wrote and configure mongodb-specific accordingly.