Bobby Wan-Kenobi
Bobby Wan-Kenobi

Reputation: 915

Running mongoimport inside a Docker container

I'm using the official MongoDB Docker image, and trying to initialize a Mongo database by placing the following script under docker-entrypoint-initdb.d:

tail -n +1 ../datasets/things.csv | mongoimport --db=test --collection=things --type=csv --fieldFile=../datasets/fields.csv --username=root --password=example

This is what my compose.yml looks like:

version: '3.8'

services:
  mongo:
    image: mongo
    restart: always
    environment:
      MONGO_INITDB_DATABASE: test
      MONGO_INITDB_ROOT_USERNAME: root
      MONGO_INITDB_ROOT_PASSWORD: example
    volumes:
      - ./docker/mongo/datasets:/datasets
      - ./docker/mongo/db_init.sh:/docker-entrypoint-initdb.d/db_init.sh

The DB is not populated, and when I drop in into the container to run manually the script I get the *error:

root@44254ca5310f:/docker-entrypoint-initdb.d# . db_init.sh 
2022-12-28T14:46:51.509+0000    error connecting to host: could not connect to server: connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.

Any help will be greatly appreciated :-)

Upvotes: 0

Views: 188

Answers (1)

Bobby Wan-Kenobi
Bobby Wan-Kenobi

Reputation: 915

Thanks to @WernfriedDomscheit for sending me down the right track. The official docs for the mongo docker image refer to the MONGO_INITDB_DATABASE as the name of a database to be used for creation scripts in /docker-entrypoint-initdb.d/*.js. Since I used test as a value in my compose.yml, I thought that was the name to use as value for the authenticationDatabase parameter. But no, it must be equal to admin. So there are twoish ways for specifying it:

tail -n +1 ../datasets/things.csv | mongoimport --collection=things --type=csv --fieldFile=../datasets/fields.csv mongodb://root:example@mongo:27017/admin

That would import the collection into admin database. But if we want to import into the test database, we have to run:

tail -n +1 ../datasets/things.csv | mongoimport --collection=things --type=csv --fieldFile=../datasets/fields.csv --username=root --password=example --authenticationDatabase=admin

Also, using --db allows us to specify the name of the database.

Upvotes: 1

Related Questions