繁体   English   中英

Dockerfile 中的 Mongorestore

[英]Mongorestore in a Dockerfile

我想创建一个启动 mongo 服务器并在启动时自动从以前的mongodump恢复的 Docker 映像。


这是我的图像的 Dockerfile:

 FROM mongo

 COPY dump /home/dump

 CMD mongorestore /home/dump

当我运行这个时,我遇到了这个错误:

Failed: error connecting to db server: no reachable servers


有没有办法让mongorestore命令通过 Docker 运行?

这个答案、Marc Young 的答案和 Dockerfile 参考的帮助下,我能够完成这项工作。


Dockerfile

FROM mongo

COPY dump /home/dump
COPY mongo.sh /home/mongo.sh
RUN chmod 777 /home/mongo.sh

CMD /home/mongo.sh

mongo.sh

#!/bin/bash

# Initialize a mongo data folder and logfile
mkdir -p /data/db
touch /var/log/mongodb.log
chmod 777 /var/log/mongodb.log

# Start mongodb with logging
# --logpath    Without this mongod will output all log information to the standard output.
# --logappend  Ensure mongod appends new entries to the end of the logfile. We create it first so that the below tail always finds something
/entrypoint.sh mongod --logpath /var/log/mongodb.log --logappend &

# Wait until mongo logs that it's ready (or timeout after 60s)
COUNTER=0
grep -q 'waiting for connections on port' /var/log/mongodb.log
while [[ $? -ne 0 && $COUNTER -lt 60 ]] ; do
    sleep 2
    let COUNTER+=2
    echo "Waiting for mongo to initialize... ($COUNTER seconds so far)"
    grep -q 'waiting for connections on port' /var/log/mongodb.log
done

# Restore from dump
mongorestore --drop /home/dump

# Keep container running
tail -f /dev/null

这是一个老问题,上面的解决方案仍然可以工作,但在以后的版本中,您可以在/docker-entrypoint-initdb.d/添加.sh.js脚本,这将在实例首次加载时执行( /data/db为空)。

现在,Dockerfile 可能看起来像:

FROM mongo

COPY ./data-dump/ /tmp/dump/mydb/

COPY ./import_data.sh /docker-entrypoint-initdb.d/import_data.sh

CMD chmod 777 /docker-entrypoint-initdb.d/import_data.sh #this is probably too permissive

这样,第一次启动容器时, import_data.sh任何内容(或您在那里拥有的任何其他文件)都将运行。

# change the mongorestore command to match your case, adding user/password and other options.
mongorestore /tmp/dump # note we can possibly restore many DBs. 

此处记录初始化新实例部分下

与 RyanNHG 类似的解决方案,但没有 sh 文件。

Dockerfile

FROM mongo:3.6.8

COPY dump/ /tmp/dump/

CMD mongod --fork --logpath /var/log/mongodb.log; \
    mongorestore /tmp/dump/; \
    mongod --shutdown; \
    docker-entrypoint.sh mongod

问题不在于docker。

如果您查看mongodockerfile,它会运行CMD ["mongod"]来启动 mongo 服务。

你说FROM MONGO但你覆盖了CMD行。 这意味着 mongo 从未通过mongod启动。 所以试试CMD mongod; mongorestore /home/dump CMD mongod; mongorestore /home/dump

您可能不想将其用于生产,但它可以满足您的需求:

== Dockerfile ==
FROM mongo:3

COPY restore.sh /restore.sh
COPY ./mongodump /dump/

ENTRYPOINT /restore.sh

那么

== restore.sh ==
#!/usr/bin/env bash

# Execute restore in the background after 5s
# https://docs.docker.com/engine/reference/run/#detached--d
sleep 5 && mongorestore /dump &

# Keep mongod in the foreground, otherwise the container will stop
docker-entrypoint.sh mongod

暂无
暂无

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

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