I try to set up a mongodb in a Dockerfile.
This is from my dockerfile which is based on Debian:
...mongoDB is installed here
#start the mongoDB
RUN mongod --fork --logpath /var/log/mongod.log
RUN mongo --eval "db.getSiblingDB('db')"
When I try to build this Dockerfile I get the following error:
connecting to: mongodb://127.0.0.1:27017
W NETWORK [thread1] Failed to connect to 127.0.0.1:27017, in(checking socket for error after poll), reason: Connection refused
E QUERY [thread1] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed : connect@src/mongo/shell/mongo.js:251:13
@(connect):1:6
exception: connect failed
It would be great, if anyone knew how to fix this issue.
The problem is related to how Docker processes the Dockerfile. Each statement in the Dockerfile is executed in a container, which was created from the image of the previous line. In case of the RUN
statement, Docker runs the code in a container and creates a new image based on the current state of the container. The image does not contain any information about running processes.
In your case, this means you have an image, which contains the mongodb
installation. Let's call it A
(instead of hash values from the docker build
log). The first RUN
statement
RUN mongod --fork --logpath /var/log/mongod.log
is processed in a container, let's call it a
, which is based on image A
. The process mongod
in a
probably appends a few lines to the log file. Once the RUN
statement has been processed, the container's file system is frozen and labeled as image B
. A Docker image does not contain any information about running processes. In fact, at this point, there is not mongod
process running anymore. However, image B
contains the log entries from this previous RUN
.
The second RUN
statement
RUN mongo --eval "use db"
is executed in container b
, which is based on image B
. This commands fails because there is no running process to which mongo
could talk to.
I think there are two solutions to your problem:
In general, you can run both scripts in one step
RUN mongod --fork --logpath /var/log/mongod.log && mongo --eval "use db"
or move them to a bash script, such that they are executed in the same container.
Use the official mongo
image on Docker hub.