如何在docker-compose之后运行Mongo shell命令?

时间:2018-05-25 21:04:10

标签: mongodb docker docker-compose

我想启动这个MongoDB副本集:

version: "3"

services:
  mongo1:
    image: mongo
    ports:
      - 27017:27017
    command: mongod --replSet rs0
  mongo2:
    image: mongo
    ports:
      - 27018:27017
    command: mongod --replSet rs0
  mongo3:
    image: mongo
    ports:
      - 27019:27017
    command: mongod --replSet rs0

等待那些人上来,然后通过终端访问Mongo shell:

docker exec -it mongo1 mongo

然后在Mongo shell中执行:

rs.initiate({"_id":"rs0","members":[{"_id":0,"host":"mongo1:27017"},{"_id":1,"host":"mongo2:27017"},{"_id":2,"host":"mongo3:27017"}]})

Mongo还允许mongo --eval "rs.initiate(..)",这可能会让事情变得更容易。

我的问题是如何在mongo1,mongo2,mongo3启动后运行此命令?

2 个答案:

答案 0 :(得分:1)

您可以执行此操作,最近我必须运行mongo --repair然后运行MongoDB本身,并且在MongoDB启动后,我需要将用户添加到数据库中,您可以轻松地更改内容以仅在运行命令后执行所有操作三个MongoDB已启动。

可能的docker-compose.yml:

version: "2"
services:
  mongo:
    container_name: mongo
    restart: on-failure:10
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=<user>
      - MONGO_INITDB_ROOT_PASSWORD=<pass>
      - MONGO_INITDB_DATABASE=db
    volumes:
      - ./data:/data/db
    ports:
      - "27017:27017"
    command: bash -c "mongod --repair && mongod"

  mongoClient:
    image: mongo
    container_name: mongoClient
    links:
      - mongo
    volumes:
      - ./deployment_scripts:/deployment_scripts
    command: 
      - /deployment_scripts/add_user.sh
    depends_on:
      - mongo

  app:
    container_name: app
    restart: always
    build: .
    volumes:
      - .:/usr/src/app
    ports:
      - "3000:3000"
    depends_on:
      - mongoClient
    links:
      - mongo

我的/deployment_scripts/add_user.sh脚本等待MongoDB启动:

until mongo --host mongo --eval "print(\"waited for connection\")"
do
    sleep 1
done

// you can add more MongoDB waits here

echo "Adding user to MongoDB..."
mongo --host mongo --eval "db.createUser({ user: \"<user>\", pwd: \"<pass>\", roles: [ { role: \"root\", db: \"admin\" } ] });"
echo "User added."

请注意,您可以通过用--host mongo --host mongo1--host mongo2替换--host mongo3来解决所有三个MongoDB。您将在脚本中的两个eval命令中使用它。

记下我使用过的该SO答案https://stackoverflow.com/a/45060399/4295037until mongo ...)。

答案 1 :(得分:-1)

我假设您正在使用Oficial Mongo图片,该图片配置为:

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["mongod"]

如果你检查docker-entrypoint.sh,你会发现你可以通过覆盖CMD来运行你想要的任何命令。

所以,你可以为每个mongo容器做

$ docker run -d mongo
9bf0473d491a2d7ae821bcf10ed08cd49678d28e46344589622bd9440a6aca65

$ docker ps -q
9bf0473d491a

$ docker exec -ti 9bf0473d491a mongo --eval "rs.initiate(.....)"
MongoDB shell version v3.6.5
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.5
{
    "ok" : 0,
    "errmsg" : "This node was not started with the replSet option",
    "code" : 76,
    "codeName" : "NoReplicationEnabled"
}

请注意,errmsg只是因为在我的示例中rs.initiate()为空,它将适用于您正确的配置。