简体   繁体   中英

Running node js app inside a container refuse to establish connection with mongo db

I am trying to execute node js app inside aa running container while mongo db container is running and up to air (docker run -d --name mongodb p 27017:27017 mongo)

This is the node js code which work perfectly with ide and throw connection error when running it on container

FAILED TO CONNECT TO MONGODB MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017

mongoose.connect(
  // `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@mongodb:27017/course-goals?authSource=admin`,
// `mongodb://${process.env.MONGODB_USERNAME}:${process.env.MONGODB_PASSWORD}@${process.env.MONGO_DB_URL}:27017/course-goals?authSource=admin`,
`mongodb://localhost:27017/course-goals?authSource=admin`,
  {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  },
  (err) => {
    if (err) {
     
      console.error(err);
    } else {
   
      app.listen(80);
    }
  }
);

I the command for the running the server docker run --name server -p 80:80 --rm server

node js docker file

FROM node

WORKDIR /app

COPY package.json .

RUN npm install

COPY . .

EXPOSE 80

CMD [ "node", "app.js" ]

I need to running it just as described, two separately container exposed port 80 for server and the other 27017 for mongo.

Thanks guys

I've used wrong address, instead of using "localhost" we should use "host.docker.internal" when saying localhost its refer to docker network localhost, but when saying "host.docker.internal" its mean for the hosting machine localhost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM