skip to Main Content

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


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

    Login or Signup to reply.
  2. A Docker container runs a single application.

    The mongo container runs CMD ["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 original docker-entrypoint.sh script (not your entrypoint.sh) will read *.js and *.sh files in the directory /docker-entrypoint-initdb.d. To quote the README:

    Initializing a fresh instance

    When a container is started for the first time it will execute files with extensions .sh and .js that are found in /docker-entrypoint-initdb.d. Files will be executed in alphabetical order. .js files will be executed by mongosh (mongo on versions below 6) using the database specified by the MONGO_INITDB_DATABASE variable, if it is present, or test otherwise. You may also switch databases within the .js script.

    So remove your ENTRYPOINT and CMD instructions and replace COPY /scripts /scripts with COPY ./scripts /docker-entrypoint-initdb.d.

    The original docker-entrypoint.d will start the Mongodb process and then execute the *.sh files (or Javascript files).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search