I have a web server written in java that connect to mongo db
my docker-compose file is:
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
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.
For more info look at this doc: https://docs.docker.com/compose/networking/#links
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.