I’m setting up MongoDB at local use official image from MongoDB and activate replica set, but I met error when run mongosh command via entrypoint (It’s still work if I ssh to container and run script).
Dockerfile
FROM mongo:6
COPY /certs /certs
COPY /scripts /scripts
EXPOSE 27017
CMD ["bash", "/scripts/setup.sh"]
ENTRYPOINT [ "bash", "/scripts/entrypoint.sh" ]
/scripts/entrypoint.sh
echo "=== Start MongoDB replica set setup ==="
echo "** Setup replica set **"
mongosh --eval "rs.initiate({_id: 'dbrs', members: [{_id: 0, host: 'localhost:27017'}]})"
echo "=== Complete MongoDB replica set setup ==="
And error thrown when execute this bash file via entrypoint: MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017
Have any solution to fix it? Thanks.
2
Answers
Add a delay before mongosh command then we can ensure that the MongoDB server has enough time to initialize.
NOTE – modify entrypoint.sh script to add a delay:
A Docker container runs a single application.
The
mongo
container runsCMD ["mongod"]
to start the Mongodb process, which you’re overwriting with your bash script.Luckily, you don’t need to do that.
Like many other Docker images, the
mongo
container has a directory where you can place startup scripts. The originaldocker-entrypoint.sh
script (not yourentrypoint.sh
) will read*.js
and*.sh
files in the directory/docker-entrypoint-initdb.d
. To quote the README:So remove your
ENTRYPOINT
andCMD
instructions and replaceCOPY /scripts /scripts
withCOPY ./scripts /docker-entrypoint-initdb.d
.The original
docker-entrypoint.d
will start the Mongodb process and then execute the*.sh
files (or Javascript files).