简体   繁体   中英

docker-compose: Connect to mongodb using node

I'm looking for some help on how I can connect to a mongodb using node in two different containers.

I have three services set up in my docker compose:

  • webserver (irrelevant to question)
  • nodeJs
  • mongo database

The nodejs container is essentially an api which I can use to communicate with mongodb:

require('dotenv').config();

const express = require('express');
const cors = require('cors')
const app = express();

var MongoClient = require('mongodb').MongoClient;
var mongodb = require('mongodb');

app.use(express.json())
app.use(cors())

app.post('/api/fetch-items', (req, res) => {
    if (req.headers.apikey !== process.env.API_KEY) return res.sendStatus(401)

    // URL is in the format: mongodb://user:pwd@database:27017
    MongoClient.connect(process.env.MONGODB_URL, function(err, db) {
        if (err) return res.status(500).send(err);
        var dbo = db.db("db");
        dbo.collection("col").find({}).toArray(function(err, result) {
            if (err) return res.status(500).send(err);
            db.close();
            return res.status(200).send(result);
        });
    });
})

app.listen(4000)

This all works perfectly fine if I run node as a standalone container (not using docker-compose) and use localhost in the URL.

However, when I use the image in docker-compose I receive the response:

{
    "name": "MongoNetworkError"
}

when sending a request to the API.

I am currently using the hostname 'database' in the URL and this does not work. I have also tried using localhost.

There are also no errors as a result of the command node server .

If needed my Dockerfile for the node server is:

FROM node:10-alpine

RUN mkdir -p /home/node/app/node_modules && chown -R node:node /home/node/app

WORKDIR /home/node/app

COPY package*.json ./

RUN chown node:node ./package*.json

USER node

RUN npm install

COPY --chown=node:node . .

EXPOSE 4000

CMD [ "node", "server" ]

My docker-compose.yml file:

version: "3.1"

services:
  mongodb:
    image: mongo
    restart: always
    container_name: database
    ports:
      - 27017:27017
    environment:
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: xxxxxxxx


  # Web server stuff

  node:
    image: created-node-server
    container_name: node
    ports:
      - 4000:4000

Finally, the output of docker network inspect:

[
    {
        "Name": "network_default",
        "Id": "3e51a90a23f2785cfc405243ad4c73991852f52826fd1cd0b14da5d4eaa180e4",
        "Created": "2021-01-12T01:07:42.656013002Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.23.0.0/16",
                    "Gateway": "172.23.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {
            "418876a06c3f8fa430804ae77c66cca986a49dbc88374266346463f7f448baa7": {
                "Name": "database",
                "EndpointID": "ac08c5a439edd43e612723d269714e9dfbae29dbdb50790b61c66207287d70c8",
                "MacAddress": "02:42:ac:17:00:04",
                "IPv4Address": "172.23.0.4/16",
                "IPv6Address": ""
            },
            "7b6dcbb8f76618575c988a026ac0308075a116f79a2e58d8a146e33fb5d7674c": {
                "Name": "node",
                "EndpointID": "e6beb412a2fe97ae7d04d2484a7ca3634bfa37c82680becc412d1f44502da72f",
                "MacAddress": "02:42:ac:17:00:03",
                "IPv4Address": "172.23.0.3/16",
                "IPv6Address": ""
            },
            "f2ea250bccdb2c6a0c4d7818912ddbf29196eff072dad699e8dbcef466cd38a3": {
                "Name": "webserver",
                "EndpointID": "f6617aab4001032069e68300c5303fa730f3458e2fe0092ace45a9f67e16d7c5",
                "MacAddress": "02:42:ac:17:00:02",
                "IPv4Address": "172.23.0.2/16",
                "IPv6Address": ""
            }
        },
        "Options": {},
        "Labels": {
            "com.docker.compose.network": "default",
            "com.docker.compose.project": "proj",
            "com.docker.compose.version": "1.27.4"
        }
    }
]

Essentially, I am retrieving the MongoNetworkError when trying to communicate with mongodb through node, both of which are docker containers created using docker-compose.

I hope all the above makes sense, sorry if it is a bit wordy, I have tried to include as much info as possible. Comment if you need any more info

Thanks:)

You just need to include an environmental variable under the node service MONGODB_URL=mongodb://database:27017

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