Search code examples
node.jsmongodbdockeraws-sam-cli

connect to mongodb in docker from node app in AWS SAM


I am getting errors connecting to mongodb running in a docker container from my Nodejs app running in AWS SAM (used to say "in my host").

I run mongodb like:

$ docker run --name mongo-myapp --rm -d -p 27018:27017 mongo

and I see the results:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
ab8248d17d2d        mongo               "docker-entrypoint.s…"   6 minutes ago       Up 6 minutes        0.0.0.0:27018->27017/tcp   mongo-myapp

~~I can successfully connect and insert data using clients running on my host like MongoDB Compass and Robo 3T Community Edition, specifying port 27018.~~

When I attempt to connect with this code running on my host, (not in a docker container):

const { MongoClient } = require('mongodb');
const mongoConnection = 'mongodb://127.0.0.1:27018';
MongoClient.connect(mongoConnection, (err, db) => {
    if (err) {
        console.error("Failed to connect to mongodb server", err);
        return reject(err);
    }
    console.log("Connected successfully to mongodb server");
    resolve(db);
});

I always see the error:

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27018

I get the same error using another port with all steps, like 27017.


UPDATE

It turns out my code was not running on the host. It was running in another docker container. I did not realize AWS SAM would put my code into a docker container so I did not mention it in the original question.

Now I run my code with mocha test to make sure it will run on my host, and it connects to the mongo database with no problems.

When I launched a local server using AWS SAM's start-api, I had problems. Perhaps the solution will be to specify a network when starting the mongo container as well as the SAM environment.


Solution

  • Now that the problem is known that the Nodejs code was running within a docker container created by AWS SAM, we can help the Nodejs code connect with Mongodb running in a separate docker container with a port exposed on the host with at least one solution:

    1. Change the connection string to mongodb://host.docker.internal:27018 which helps the code in the container to use a service running on the host.