1

I'm trying to run a mongo script on a docker container using this command docker run --rm -it --volume "$(pwd):/scripts" mongo:latest mongo /scripts/${SCRIPT_FILE_NAME}, and I'm keeping getting this error:

MongoDB shell version v4.4.0
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:362:17
@(connect):2:6
exception: connect failed
exiting with code 1
Yasin Mansour
  • 119
  • 1
  • 1
  • 6

1 Answers1

0

The docker run command that you shared attempts to execute explicitly the mongo /scripts/${SCRIPT_FILE_NAME} command, immediately when the container is started.
At that point in time, the mongodb daemon isn't ready to accept connections(yet).

Instead of trying to initialize manually, you should leverage the built-in mongo mechanism that discovers the scripts under /docker-entrypoint-initdb.d and executes them when the DB is running.

When a mongo 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 mongo 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.

Check the mongo image official documentation for more details.

Neo Anderson
  • 5,957
  • 2
  • 12
  • 29
  • I thought that this is the issue but according to this answer (https://stackoverflow.com/a/32944935) this command should also work. if it worked for him then there is something else happening on my machine. – Yasin Mansour Sep 09 '20 at 21:16
  • @YasinMansour The command is fine. Again: you are executing it too soon. The mongo db is taking a couple of seconds to become available, when the container is started. Your `mongo /scripts/${SCRIPT_FILE_NAME}` command is executed when mongo DB isn't running yet. As for the answer you shared, I am pretty sure that the first command (`docker run -it -p 28000:27017 --name mongoContainer mongo:latest mongo`) fails with a similar error as yours. Do the test yourself. Then, do a second test: start a mongo container with no argument and try with the second command from that example and it will work – Neo Anderson Sep 10 '20 at 12:54