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.
>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: