Cannot connect to MongoDB in docker
You have to tell the container to use it's own IP Address instead of localhost.
For example, let's assume you generated scaffold code with expressjs
, you have to write in routes/index.js
var mongodb = require('mongodb');
router.get('/thelist', function(req, res){
// Get a Mongo client to work with the Mongo server
var MongoClient = mongodb.MongoClient;
// Define where the MongoDB server is
var url = 'mongodb://172.17.0.5:27017/dbname';
// Connect to the server
MongoClient.connect(url, function (err, db) {
.........
where 172.17.0.5
is the $CONTAINER_IP
you can find the container ip via
$ docker inspect $CONTAINER_NAME | grep IPAddress
If no internet in container
Open with sudo sudo vim /etc/NetworkManager/NetworkManager.conf
and comment out the line dns=dnsmasq
, so you would now have:
[main]
plugins=ifupdown,keyfile,ofono
#dns=dnsmasq
[ifupdown]
managed=false
Edit: service name instead of IP
You may now use service name instead of IP Address of the container, eg:
// Define where the MongoDB server is
var url = 'mongodb://api:27017/dbname';
The gotcha here is - if a container listens on 127.0.0.1, then the host can't map ports to it.
You need to listen on 0.0.0.0
or similar, and then the -p
can reach the container's interface.
I had the same problem but found another way to address this issue. You can just pass network parameter while running docker image and this way docker points to correct localhost.
docker run --network="host" ....
Source for this solution