首页 > 解决方案 > 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?

标签: mongodbdockerdocker-composeazure-functions

解决方案


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


推荐阅读