mongodb - Unable to connect to the mongodb instance running in a docker container from inside the container
问题描述
I have built a docker container consisting of a mongodb database and an azure http-triggered function. The following yaml is the docker compose file:
version: '3.4'
services:
mongo:
image: mongo
container_name: mongodb
restart: always
ports:
- 37017:27017
storage.emulator:
image: "mcr.microsoft.com/azure-storage/azurite:latest"
container_name: storage.emulator
ports:
- 20000:10000
- 20001:10001
- 20002:10002
my.functions:
image: ${DOCKER_REGISTRY-}myfunctions
build:
context: .
dockerfile: domain/My.Functions/Dockerfile
ports:
- 9080:80
depends_on:
- storage.emulator
- mongo
The mongodb instance runs well and I am able to connect to it from outside of the container by mongodb://localhost:37017
connection string to seed some data.
The Azure Function running inside the container is supposed to communicate with the mongodb instance by mongodb://localhost:27017
connection string but it fails according to the following error message:
"Unspecified/localhost:27017", ReasonChanged: "Heartbeat", State: "Disconnected", ServerVersion: , TopologyVersion: , Type: "Unknown", HeartbeatException: "MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. my.functions_1 | ---> System.Net.Sockets.SocketException (99): Cannot assign requested address
How can I address this problem? Why the mongodb is unavailable internally to the azure function within the same container?
解决方案
Because docker containers runs on isolated networks of their own. So when you try to connect localhost, actually you are trying to my.functions app and obviously it does not have service running on that part.
You should use docker-compose service name
mongodb://mongo:27017
推荐阅读
- search - 了解 Solr 函数查询性能
- javascript - 在反应中使用`Clipboard.js`引发错误:第一个参数必须是字符串,HTMLElement,
- python - 如何在 pip(pypi) 模块中包含 txt 文件
- mysql - 如何使用终端从远程服务器执行“mysqldump”并在本地保存
- vert.x - Vertx:如何将路由器分离到不同的类以保持单个顶点
- javascript - 如何设计嵌套的 3 级 json
- sonarqube - 如何忽略 SonarQube 扫描仪中的所有 .scss 文件?
- wordpress - 如何在 WP 标题中显示滑块并运行?
- elasticsearch - 使用无痛脚本聚合嵌套文档
- c# - UWP Slider 的动画拇指