我正在尝试搭建一个运行 MongoDB 的容器,当它启动时使用 mongorestore 来填充数据。这个想法是为了快速设置一个虚拟数据库以用于测试和模拟。
我的 Dockerfile 如下:
FROM mongo:bionic
COPY ./db-dump/mydatabase/* /db-dump/
而docker-compose.yml看起来像这样:
version: "3.1"
services:
mongo:
build: ./mongo
command: mongorestore -d mydatabase ./db-dump
ports:
- "27017:27017"
如果我使用
docker-compose up
运行它,它会暂停一段时间然后出现错误,提示:error connecting to host: could not connect to server: server selection error: server selection timeout, current topology: { Type: Single, Servers: [{ Addr: localhost:27017, Type: Unknown, State: Connected, Average RTT: 0, Last error: connection() : dial tcp 127.0.0.1:27017: connect: connection refused }, ] }
在容器上打开CLI并运行相同的命令时没有任何问题。但是,我尝试添加
-h
与容器名称或127.0.0.1一起使用,却没有任何区别。为什么这个命令不能连接,而在容器运行时它能够正常工作呢?