Home > other >  Connect mongo docker container with node.js
Connect mongo docker container with node.js

Time:01-14

docker-compose.yml:

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

index.js:

const mongoose = require('mongoose')

mongoose
    .set('strictQuery', false)
    .connect('mongodb://root:example@mongo:27017/')
    .then(() => console.log('Connected!'))
    .catch((e) => console.log('Mongo Error:', e.message))


const Book = mongoose.model('Book', new mongoose.Schema({
    title: {
        type: String,
        required: true,
        unique: true,
        minlength: 2
    },
    published: {
        type: Number,
        required: true,
    },
    author: {
        type: String,
        required: true,
    },
}));

const book = new Book({ title: 'Harri Potter', published: 1997, author: "J. K. Rowling" })
//book.save()

package.json

{
  "name": "sb",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongoose": "^6.8.3",
    "nodemon": "^2.0.20"
  }
}

And then how to connect.

$ docker-compose up -d
....
$ npm run dev
ivo@LAPTOP-0KNMEE5S MINGW64 /c/myproj/sb (master)
$ npm run dev

> [email protected] dev
> nodemon index.js

[nodemon] 2.0.20
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node index.js`
Mongo Error: getaddrinfo ENOTFOUND mongo
[nodemon] clean exit - waiting for changes before restart

I puzzle a long time it. Can somebody help me???? Please working example. Than you forward

CodePudding user response:

You need to map your PC port to the docker one:

version: '3.1'

services:

  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example

Then in your node.js script

...
.connect('mongodb://root:[email protected]:27017/')
...

The mongo:27017 would work only if you run your node.js application inside a docker container in the same mongo container's network.

  • Related