如何利用Mongo种子容器将用户导入管理员?

时间:2019-04-03 08:57:45

标签: mongodb docker dockerfile

当我们需要在初始化mongo容器之前预先插入一些集合时,Mongo种子容器会派上用场。例如,就像这个问题的解决方案一样:How do I seed a mongo database using docker-compose?

但是如何通过以下Docker设置将用户导入到管理数据库中呢?

  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
    

    通过此设置,mongodb_seed可用于在初始化之前将就绪数据插入mongodb

  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"]
    

    使用此设置,import.sh可用于执行包含以下内容的insert_users.js的代码:

    use admin
    db.createUser()
    

    在这种情况下,import.sh可能类似于:

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

但是这种方法在日志中连接被拒绝

    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

如何解决此问题?

0 个答案:

没有答案