mongodb - Docker-在运行创建索引脚本之前等待Mongo加载

标签 mongodb docker

我有一个在MongoDB中创建文本索引的脚本-但是,如果我将其与当前的Dockerfile(反过来在我的docker-compose文件中被调用)一起使用,则会导致错误,因为Mongo尚未完全加载。

我看过dependsOn,但这似乎是针对整个服务的。也遇到这个https://github.com/ufoscout/docker-compose-wait/,但是如果有更简单的东西,我想避免使用它。

有谁解决了这个问题-等待Mongo在RUN之前加载?

我的dockerfile

FROM mongo:4
COPY ./scripts /scripts
RUN mongo<scripts/create-text-indexes

和docker-compose代码段:
dashboard-mongo:
    build:
      context: ./infrastructure
      dockerfile: Dockerfile
    image: a-custom-mongo:SNAPSHOT
    ports:
      - "27017:27017"
    networks:
      default:
      cms:
        aliases:
          - dashboard-mongo

我正在运行的脚本如下所示:
use customboard

print("---> Deleting existing indexes...");
db.test.dropIndexes();

print("---> Creating indexes...");
db.test.createIndex({
    "_id": "text",
    "code": "text"
});

谢谢。

最佳答案

RUN mongo<scripts/create-text-indexes此脚本将不起作用,请记住RUN命令用于安装和配置,以免与数据库交互或启动该过程。您应该在CMD或入口点开始该过程。

一种使用offical imageclone the offical存储库并从官方docker镜像入口点中受益的方法。为什么要重新发明轮子?

知道您所需要的官方图像

FROM mongo:4
COPY ./scripts /docker-entrypoint-initdb.d

一旦构建并启动容器,正式镜像将启动DB进程,并等待它能够处理连接,然后它将运行脚本。

初始化一个新实例

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.



docker mongo image

关于mongodb - Docker-在运行创建索引脚本之前等待Mongo加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58796850/

相关文章:

javascript - 如何改变JSON格式?

mongodb - Mongoose 没有自动增加 __v

docker - 为什么 docker-compose up 似乎不同步卷

docker - 无法连接到转发任何端口的 docker 端口

jenkins - Jenkins-Docker集成-使用Jenkins构建Docker镜像并推送到注册表

springboot中docker连接Mongodb报错

node.js - Mongoose.js 仅在定义/更改时更新单个属性

java - 将 "value in array column"MongoDB 查询转换为 MongoDB Spring Data 代码

python - 为什么 pipenv 无法在 docker 容器中安装包

c# - 无法在 Docker 上运行 asp.net mvc 6