运行 容器启动后 Docker 上的 mongorestore

Running mongorestore on Docker once the container starts

我正在尝试设置一个容器 运行ning 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 并 运行使用完全相同的命令,但是没有任何问题。我试过用容器名称或 127.0.0.1 添加 -h,但没有任何区别。为什么这个命令在容器 运行ning 后正常工作时无法连接?

有比覆盖默认命令更好的方法 - 使用 /docker-entrypoint-initdb.d:

When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongo using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

[Source]

所以您只需将该命令写入名为 mongorestore.sh:

的文件中
mongorestore -d mydatabase /db-dump

然后将其与转储文件一起安装到内部:

version: "3.1"
  
services:
  mongo:
    image: mongo:bionic
    ports:
      - "27017:27017"
    volumes:
      - ./mongorestore.sh:/docker-entrypoint-initdb.d/mongorestore.sh
      - ./db-dump:/db-dump

您甚至不需要 Dockerfile。