22

我想创建一个启动 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 运行?

4

5 回答 5

18

这个答案、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

于 2016-09-02T04:46:27.040 回答
11

这是一个老问题,上面的解决方案仍然可以工作,但在以后的版本中,您可以添加.sh.js脚本/docker-entrypoint-initdb.d/,以防实例首次加载(/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. 

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

于 2019-03-17T16:53:46.777 回答
11

与 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
于 2018-11-29T09:57:25.607 回答
2

问题不在于码头工人。

如果您查看mongo 的 dockerfile,它将运行CMD ["mongod"]启动 mongo 服务。

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

于 2016-09-02T02:41:47.363 回答
0

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

== 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
于 2017-06-22T00:19:08.837 回答