简体   繁体   English

使用 docker-compose 连接到 mongodb 失败

[英]Failed to connect to mongodb with docker-compose

I have a web server written in java that connect to mongo db我有一个 web 服务器,用 java 编写,连接到 mongo db

my docker-compose file is:我的 docker-compose 文件是:

version: "3.2"

services:

  web:
    image: org/web-server:latest
    restart: always
    env_file: .env
    depends_on: 
      - mongo
    ports:     
     - "8080:9999"
    networks:
      - web-network
  mongo:
    image: mongo
    restart: always
    ports:
      - 27017:27017
    networks: 
      - web-network
    volumes: 
      - "mongodbdata:/data/db"

networks:
    web-network:
volumes: 
    mongodbdata:

Exception is:例外是:

org.mongodb.driver.cluster - Exception in monitor thread while connecting to server localhost:27017
bot_1    | com.mongodb.MongoSocketOpenException: Exception opening socket
bot_1    |  at com.mongodb.internal.connection.AsynchronousSocketChannelStream$OpenCompletionHandler.failed(AsynchronousSocketChannelStream.java:124)
bot_1    |  at sun.nio.ch.Invoker.invokeUnchecked(Invoker.java:128)
bot_1    |  at sun.nio.ch.Invoker$2.run(Invoker.java:218)
bot_1    |  at sun.nio.ch.AsynchronousChannelGroupImpl$1.run(AsynchronousChannelGroupImpl.java:112)
bot_1    |  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
bot_1    |  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
bot_1    |  at java.lang.Thread.run(Thread.java:748)
bot_1    | Caused by: java.net.ConnectException: Connection refused
bot_1    |  at sun.nio.ch.UnixAsynchronousSocketChannelImpl.checkConnect(Native Method)
bot_1    |  at sun.nio.ch.UnixAsynchronousSocketChannelImpl.finishConnect(UnixAsynchronousSocketChannelImpl.java:252)
bot_1    |  at sun.nio.ch.UnixAsynchronousSocketChannelImpl.finish(UnixAsynchronousSocketChannelImpl.java:198)
bot_1    |  at sun.nio.ch.UnixAsynchronousSocketChannelImpl.onEvent(UnixAsynchronousSocketChannelImpl.java:213)
bot_1    |  at sun.nio.ch.EPollPort$EventHandlerTask.run(EPollPort.java:293)
bot_1    |  ... 1 common frames omitted

When you try to connect to mongo with mongodb://localhost:27017 your application look for local container which is the one that host only the app name web in docker compose当您尝试使用mongodb://localhost:27017连接到 mongo 时,您的应用程序会查找本地容器,该容器仅在 Z05B6053C41A2130AFD6FC3B158BDA4E 中托管应用程序名称web

The easiest way to solve this problem is to set your uri to mongodb://mongo:27017 But if you like you use mongodb://localhost:27017 you should use Link option in docker compose.解决此问题的最简单方法是将您的 uri 设置为mongodb://mongo:27017但如果您喜欢使用mongodb://localhost:27017 ,您应该使用 Z05B6053C41A21340AFDBEDB 中的Link选项。

For more info look at this doc: https://docs.docker.com/compose/networking/#links有关更多信息,请查看此文档: https://docs.docker.com/compose/networking/#links

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM