Problem
I needed multiple docker containers to communicate with each other, through network calls.
Solution
Using "BRIDGE & OVERLAY network modes"
Connect Containers in Same Docker Host
Bridge Network Mode - allows containers connected to the same bridge network to communicate, while providing isolation from containers which are not connected to that bridge network.
A default bridge called "bridge" is always created between all the containers in the host.
Connect Containers in Different Docker Host
Overlays Network Mode - this network sits on top of the host-specific networks, allowing containers connected to it to communicate securely when encryption is enabled.
For each container you want to add to the network, add the following in docker-compose file.
networks:
- local //{network_name}
and at the end of the file, add the following
networks:
local: // {network_name}
driver: bridge
Finally, docker-compose looks like this
local-redis:
image: redis
ports:
- "6379:6379"
volumes:
- redis-data:/data
networks:
- local
local-mongo:
image: mongo:3.2
command: ["mongod", "--smallfiles"]
ports:
- "27017:27017"
volumes:
- mongo-data:/data/db
networks:
- local
networks:
local:
driver: bridge
And, this is how you make network calls to call other docker containers
{container_name}:{container_port}
"mongo_url": "mongodb://local-mongo:27017/analytics"
"redis_host": "local-redis"
Side Note
What are Container Port & Host Port?
A Container port is the port to be used within a container, when using BRIDGE or USER networking mode.
A Host port specifies a port on the host machine to bind to.
In a docker-compose file, it looks like this,
local-application:
image: ...
ports:
- "7602:7600" //{hostPort}:{containerPort}
Inside docker code, you can call like this
"app_url": "http://local-application:7600"
Outside docker(from browser), you can call like this
http://localhost:7602/
Top comments (0)