Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error when run mongosh command from Dockerfile ENTRYPOINT

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

Add a delay before mongosh command then we can ensure that the MongoDB server has enough time to initialize.

#!/bin/bash

echo "=== Start MongoDB replica set setup ==="

# Wait for MongoDB to start
echo "** Waiting for MongoDB to start **"
until mongo --eval "db.adminCommand('ping')" &>/dev/null
do
    sleep 1
done

echo "** MongoDB started, setting up replica set **"
mongosh --eval "rs.initiate({_id: 'dbrs', members: [{_id: 0, host: 'localhost:27017'}]})"

echo "=== Complete MongoDB replica set setup ==="

NOTE – modify entrypoint.sh script to add a delay:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading