Parvathi
Posted on October 8, 2021
Beginner's guide to Docker(Part 1)- Dockerfile and Docker CLI commands
Parvathi γ» Sep 27 '21 γ» 8 min read
Beginner's Guide to Docker(Part 2)- Manage data in Docker
Parvathi γ» Sep 29 '21 γ» 5 min read
We have learned about docker basics and also we saw what is volumes and why we need volume in docker. Now let us see what are all the types of communication our application needs and how we can achieve it using docker.
Container to WWW
In case, our application in docker container wants to communicate with world wide web for read or write, for example, our application uses youtube api to fetch video for our iframe, or building any search widget using wikipedia api we need to communicate with api that youtube and wikipedia has exposed, this we can do it without any additional efforts, docker supports this out of box.
Container to host
Let's say we have our application is in need to connect with mongodb which is hosted on localhost, now what can we do? how our application inside container reaches the mongodb hosted locally?
mongoose.connect('mongodb://localhost/todo_app', {useNewUrlParser: true, useUnifiedTopology: true});
we can simply change the above code to
mongoose.connect('mongodb://host.docker.internal/todo_app', {useNewUrlParser: true, useUnifiedTopology: true});
Container to another container
Let's take the same above example, our application wants to communicate with the mongodb, but this time it is hosted in another container instead of host machine, now how can we do that?
docker run --name mongoDb --rm -d -v data:/data/db mongo
docker container inspect mongoDb
from the result of the above command, we can find the ipAddress of the mongo container
"IPAddress": "172.17.0.2",
We can replace the connection string as
mongoose.connect('mongodb://172.17.0.2/todo_app', {useNewUrlParser: true, useUnifiedTopology: true});
Wait is this the only way to do it??? No!
Network
docker network COMMAND
Manage networks. You can use subcommands to create, inspect, list, remove, prune, connect, and disconnect networks.
Let us take todo application built using MERN stack, in which our node application talks with mongo db.
We can bring node container and mongo container to a same network and then we can just use the container name as host ipAddress and docker will resolve the ipAddress internally.
docker network create todo-network
docker run \
--name mongodb_container \
--rm \
-d \
--network todo-network \
-v data:/data/db \
mongo
docker run \
--name todo-node \
-p 3030:3030 \
--rm \
--network todo-network \
todo-node
mongoose.connect('mongodb://mongodb_container/todo_app', {useNewUrlParser: true, useUnifiedTopology: true});
Thanks for Reading!!!
Learn more about Docker Compose in next article
Posted on October 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.