I am trying to connect an express container to MongoDB image with docker compose but the connection is being rejected, I can connect to the db with robomongo. I can't get what is happening, this is the express code that connects it:
mongoose.connect('mongodb://localhost:27017/database')
.then(()=>console.log('connection succesfull to url'))
.catch((err)=>console.error(err));
This is the docker-compose file
version: "3"
services:
backend:
build:
context: ../backend
dockerfile: ${PWD}/images/backend/Dockerfile
container_name: backend
ports:
- "${BACKEND_PORT}:${BACKEND_PORT}"
env_file:
- ./deploy.env
environment:
- PORT=3000
- MONGO_CONNECTION=${MONGO_CONNECTION}
command: npm start
links:
- mongodb
depends_on:
- mongodb
front-app:
build:
context: ../front-app
dockerfile: ${PWD}/images/angular/Dockerfile
container_name: front-app
ports:
- "${FRONTEND_PORT}:4200"
env_file:
- ./deploy.env
command: npm start
mongodb:
image: mongo:3.6
container_name: mongo
volumes:
- "${MONGO_DB_DATA}:/data/db"
- "${MONGO_DB_DATA}:/data/configdb"
ports:
- "27017:27017"
This is the error
backend | { MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
backend | at Pool.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/topologies/server.js:564:11)
backend | at Pool.emit (events.js:182:13)
backend | at Pool.EventEmitter.emit (domain.js:442:20)
backend | at Connection.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/pool.js:317:12)
backend | at Object.onceWrapper (events.js:273:13)
backend | at Connection.emit (events.js:182:13)
backend | at Connection.EventEmitter.emit (domain.js:442:20)
backend | at Socket.<anonymous> (/usr/src/app/node_modules/mongodb-core/lib/connection/connection.js:246:50)
backend | at Object.onceWrapper (events.js:273:13)
backend | at Socket.emit (events.js:182:13)
backend | at Socket.EventEmitter.emit (domain.js:442:20)
backend | at emitErrorNT (internal/streams/destroy.js:82:8)
backend | at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
backend | at process._tickCallback (internal/process/next_tick.js:63:19)
backend | name: 'MongoNetworkError',
backend | errorLabels: [ 'TransientTransactionError' ],
backend | [Symbol(mongoErrorContextSymbol)]: {} }