I created an express application configured with Mongodb for database that connect locally on my machine. I have decided to Dockerize this application and run the image as container but there seems to be a problem, my container connecting to a database on local port 27017. I figured out that my container cannot connect to any host services so I pulled mongo image from docker hub and started it, but before, I created network and started both containers with --network=mynetwork flag but still the express app container returns mongodb connection error.
Someone help
The problem is that the Express is trying to connect MongoDB on the host
127.0.0.1
which refers to the same container. You have several options to solve this, two of them are
host
This will make the containers run on the same network interface as the host, so all the ports are exposed then when the express requests 127.0.0.1
it'll reach MongoDB.
sudo docker run -d --network=host --name mongodb mongo
sudo docker run -d --network=host --name backend yolobackend:1.0.0
Because both of containers are running in the same network (mynetwork) they can communicate. Docker provides a DNS service the resolves the container's IP based on the container name only if they are in the same network and it is explicitly provided (not the default network), so changing the connection string to
mongodb://mongodb:27017
where the host is your MongoDB container name. Redeploy your application will solve your problem.
I recommend you checking out this video.