从AWS SAM中的节点应用程序连接到docker中的mongodb [英] connect to mongodb in docker from node app in AWS SAM
问题描述
我从运行在AWS SAM中的Nodejs应用程序连接到在docker容器中运行的mongodb时出错了(过去说在我的主机中)。
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").
我像这样运行mongodb:
I run mongodb like:
$ docker run --name mongo-myapp --rm -d -p 27018:27017 mongo
我看到结果:
$ 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
~~我可以成功使用我的主机(例如MongoDB Compass和Robo 3T Community Edition)上运行的客户端连接并插入数据,并指定端口27018。~~
当我尝试与之连接时此代码在我的主机上运行(不在Docker容器中):
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);
});
我总是看到错误:
MongoNetworkError:connect ECONNREFUSED 127.0.0.1:27018
我在使用所有其他步骤的端口时也遇到相同的错误27017。
I get the same error using another port with all steps, like 27017.
更新
事实证明,我的代码未在主机上运行。它正在另一个Docker容器中运行。我没有意识到 AWS SAM 会将我的代码放入docker容器中,所以我没有
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.
现在,我使用 mocha test
运行代码,以确保它可以在我的主机,它毫无问题地连接到mongo数据库。
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.
当我使用AWS SAM的 start-api ,问题。也许解决方案将是在启动mongo容器以及SAM环境时指定一个网络。
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.
推荐答案
现在,问题出在已知Nodejs代码在AWS SAM创建的docker容器中运行,我们可以通过至少一种解决方案帮助Nodejs代码与在单独的docker容器中运行且在主机上暴露端口的Mongodb连接:
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:
- 将连接字符串更改为
mongodb://host.docker.internal:27018
在容器中使用主机上运行的服务。
- 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.
这篇关于从AWS SAM中的节点应用程序连接到docker中的mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!