如何自动设置dockerized mongo副本集?

时间:2019-08-13 16:28:34

标签: mongodb docker mongodb-replica-set

我正在使用此docker-compose.yml运行本地mongo副本集:

version: '3.5'

services:
  mongo1:
    hostname: mongo1
    container_name: localmongo1
    image: mongo
    expose:
      - 27017
    ports:
      - 27017:27017
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
  mongo2:
    hostname: mongo2
    container_name: localmongo2
    image: mongo
    expose:
      - 27017
    ports:
      - 27018:27017
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]
  mongo3:
    hostname: mongo3
    container_name: localmongo3
    image: mongo
    expose:
      - 27017
    ports:
      - 27019:27017
    restart: always
    entrypoint: [ "/usr/bin/mongod", "--bind_ip_all", "--replSet", "rs0" ]  

这很简单并且工作正常,但是我必须: 1-初始化副本集:

  {
    _id : 'rs0',
    members: [
      { _id : 0, host : "mongo1:27017" },
      { _id : 1, host : "mongo2:27017" },
      { _id : 2, host : "mongo3:27017" }
    ]
  }
)

2-将多个用户添加到多个数据库:

use db1
db.createUser({  
   user:"user1",
   pwd:"pass",
   roles:[  
      {  
         role:"readWrite",
         db:"db1"
      },
      {  
         role:"dbAdmin",
         db:"db1"
      }
   ]
})

use db2
db.createUser({  
   user:"user2",
   pwd:"pass",
   roles:[  
      {  
         role:"readWrite",
         db:"db2"
      }
   ]
})

我正在尝试找到一种方法,在部署了上述3个容器之后立即运行最后两个脚本。 我应该添加另一个运行这些脚本的映像吗? 还是应该以其他方式运行这些脚本?

(其他问题涉及某些用户维护的图像。我不喜欢使用它们。)

1 个答案:

答案 0 :(得分:0)

使用ps脚本解决了该问题:

Get-Content <file>.txt -raw|docker exec -i localmongo1 mongo
exit 

一些mongo shell脚本在哪里。