Reputation: 8365
I'm trying to run a simple docker setup with node and mongo:
Dockerfile:
FROM node:8.9.4-alpine
RUN mkdir /app
WORKDIR /app
COPY package.json /app/
COPY package-lock.json /app/
RUN npm install
ADD . /app/
docker-compose.yml:
version: '3'
services:
db:
image: 'mongo'
ports:
- "27017:27017"
api:
build: .
restart: always
command: sh -c "npm install && npm run start"
volumes:
- .:/app
ports:
- "3000:3000"
environment:
PORT: 3000
depends_on:
- db
Now in my app.js I'm connecting to mongo like that:
mongoose.connect('mongodb://localhost:27017')
.catch(err => {
console.log(err)
})
However I'm getting a failed to connect to server [localhost:27017] on first connect [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017]
The mongo container seems to boot up and run fine giving me waiting for connections on port 27017
.
What's wrong with my setup? I also tried swapping out localhost
for mongo
when connecting, but it had no effect either.
Upvotes: 7
Views: 11918
Reputation: 21
Here is the fix: In docker-compose.yml:
services:
mongodb:
image: mongo:7
restart: unless-stopped
container_name: mongo-server
ports:
- 27017:27017
volumes:
- ./data:/data/db
Remember at the container_name, name it whatever you want, and then, in the mongoose connection:
mongoose.connect("mongodb://mongo-server:27017/your_table_name")
Change "mongo-server" that match container_name. Hope it helps.
Upvotes: 0
Reputation: 424
you have to look at the port part of your container in the inspector, and my opinion is that you have to put : mongodb://0.0.0.0:27017/
enjoy !
Upvotes: 1
Reputation: 1
I think without mounting volumes in db
service , container won't be able to continue its process. it will start for just a second and then it will be terminated.
so that's why you are getting an error.
Upvotes: 0
Reputation: 8365
I didn't realise I named my database container db instead of mongo, so all I had to do was to switch that name out in my app.js:
mongoose.connect('mongodb://db:27017')
.catch(err => {
console.log(err)
})
Upvotes: 14