1

Mongo seed container comes in handy when we need to pre-insert some collections before initializing a mongo container. For instance, like the solution in this question:How do I seed a mongo database using docker-compose?

But what about importing users to admin database with the following Docker set up:

  1. docker-compose.yml:

    version: '3.4'
    services:
      mongodb:
        image: mongo:latest
        ports: 
        - "27017:27017"
        environment:
        # provide your credentials here
        - MONGO_INITDB_ROOT_USERNAME=root
        - MONGO_INITDB_ROOT_PASSWORD=root
        container_name: mongodb 
      mongodb_seed:
        build: mongodb_seed
        links:
        - mongodb
    

    with this setting, mongodb_seed can be used to insert ready data into mongodb right before initializing

  2. Dockerfile of mongodb_seed:

    FROM mongo:latest
    WORKDIR /tmp
    COPY users.json .
    COPY insert_users.js .
    COPY import.sh .
    CMD ["/bin/bash", "-c", "source import.sh"]
    

    with this setting, the import.sh can be used to execute the insert_users.jscontaining code like:

    use admin
    db.createUser()
    

    in this case the import.sh might look like:

    #!/bin/bash
    mongo -u root -p root --authenticationDatabase admin insert_users.js
    

But this approach got connection refused in the log:

    mongodb_seed_1  | connecting to: mongodb://127.0.0.1:27017/? authSource=admin&gssapiServiceName=mongodb
    mongodb_seed_1  | 2019-04-03T07:39:27.902+0000 E QUERY    [js] 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 :
    mongodb_seed_1  | connect@src/mongo/shell/mongo.js:343:13
    mongodb_seed_1  | @(connect):2:6
    mongodb_seed_1  | exception: connect failed

How to resolve this issue?

Rui
  • 3,454
  • 6
  • 37
  • 70
  • As a service, MongoDB does take some time to start. So any scripting needs to take this into account. – Neil Lunn Apr 03 '19 at 09:09
  • 1
    @NeilLunn Note that I used one mongo container as the seed, and I tried to add a sleep command to wait for about half a minute before running the mongo cli command, but still got the same error. So seems that when running the CMD in the mongo seed container, the mongod service is never started at all – Rui Apr 03 '19 at 14:38
  • If you actually check both the question and answer you've been linked to, then you should notice that your own configuration completely misses asking the service to start. Those examples actually do that. – Neil Lunn Apr 04 '19 at 07:06

0 Answers0