I have to setup a mongo replica set with docker-compose. For the replica set the containers have to know each other.
I tried in docker-compose.yml
dbreplicasetpart1: image: mongo:2.6.8 expose: - '27018' links: - replicasetpart2 - replicasetpart3 cap_add: - NET_ADMIN dbreplicasetpart2: image: mongo:2.6.8 links: - replicasetpart1 - replicasetpart3 expose: - '27019' cap_add: - NET_ADMIN ...
I get an circular import message. But if I remove the back-link to dbreplicasetpart1 I can't ping from dbreplicasetpart2 to dbreplicasetpart1. What is the solution?
If you are running more than one container, you can let your containers communicate with each other by attaching them to the same network. Docker creates virtual networks which let your containers talk to each other. In a network, a container has an IP address, and optionally a hostname.
3. Docker Compose links. links instructs Docker to link containers over a network. When we link containers, Docker creates environment variables and adds containers to the known hosts list so they can discover each other.
Updated for Docker 1.10
Docker 1.10 allows the definition of networks within the compose file. Here's the updated code
version: "2" services: replica1: image: mongo:2.6.8 container_name: replica1 networks: - my-net ports: - "27018" environment: REPLICA2_URL: "http://replica2:27019" replica2: image: mongo:2.6.8 container_name: replica2 networks: - my-net ports: - "27019" environment: REPLICA1_URL: "http://replica1:27018" networks: my-net: driver: bridge
Previous answer for Docker 1.9
As of Docker 1.9, the solution to this is to create a custom network and pass it to the docker-compose up
command.
Create a network docker network create --driver bridge my-net
Reference that network as an environment variable (${NETWORK}
)in the docker-compose.yml files. Eg:
```
replica1: image: mongo:2.6.8 container_name: replica1 net: ${NETWORK} ports: - "27018" environment: REPLICA2_URL: "http://replica2:27019" replica2: image: mongo:2.6.8 container_name: replica2 net: ${NETWORK} ports: - "27019" environment: REPLICA1_URL: "http://replica1:27018"
```
Note that replica1
in http://replica1:27018
will resolve to the ip address of the replica1 service (container). No need to hardcode ip addresses; An entry for replica1 is automatically added to the /etc/host of the replica2 container. Same goes for the replica1 container. Docker will add an entry for replica2 in its /etc/host file.
NETWORK=my-net docker-compose up -d -f docker-compose.yml
I've created a bridge network above which only works within one node (host). Good for dev. If you need to get two nodes to talk to each other, you need to create an overlay network. Same principle though. You pass the network name to the docker-compose up command.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With