I have been learning docker lately and I was unable to make a connection between my loopback api and mongodb. The application works fine in local dev environment. With docker-compose my mongodb server runs at localhost:27017
and my react-frontend serves at localhost:3000
and looks fine. Only loopback is unable to connect to mongodb and throws the following errors:
loopback_1 | Web server listening at: http://localhost:8080
loopback_1 | Browse your REST API at http://localhost:8080/explorer
loopback_1 | Connection fails: MongoError: failed to connect to server
[localhost:27017] on first connect [MongoError: connect ECONNREFUSED
127.0.0.1:27017]
loopback_1 | It will be retried for the next request.
loopback_1 |
loopback_1 | /opt/src/app/node_modules/mongodb/lib/mongo_client.js:421
loopback_1 | throw err
loopback_1 | ^
loopback_1 | MongoError: failed to connect to server [localhost:27017]
on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
loopback_1 | at Pool.<anonymous>
(/opt/src/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)
Here is my Dockerfile for Loopback-API
FROM node:6
RUN mkdir -p /opt/src/app
WORKDIR /opt/src/app
COPY package.json /opt/src/app
RUN npm cache clean
RUN npm install
COPY . /opt/src/app
EXPOSE 8080
CMD ["npm", "start"]
My docker-compose file looks like this:
version: '3.0' # specify docker-compose version
# Define the services/containers to be run
services:
database: # name of first service
image: mongo # specify the image to build container from
ports:
- "27017:27017" # specify port forwarding
loopback: # name of second service
build: myapp_backend # specify the directory of the Dockerfile
ports:
- "8080:8080" # specify port mapping
links:
- database # link this service to the database service
react: # name of third service
build: myapp_frontend # specify the directory of the Dockerfile
ports:
- "3000:3000" #specify port mapping
And finally datasource file in loopback-api looks like this:
{
"db": {
"host": "localhost",
"port": 27017,
"url": "",
"database": "test",
"password": "",
"name": "mongoDS",
"user": "",
"connector": "mongodb"
}
}
Your datasource file should have:
"host": "database" ...
since in docker-compose.yml you link mongo container to loopback as
database
, so it's notlocalhost
. Remember, you are trying to connect to mongo from loopback docker container. Also you should make sure that mongo is started before loopback, so adddepends_on: database
to loopback service in docker-compose.yml.