docker-compose deploy replicaSet in standalone MongoDB cluster and with auth

经过两天的折腾,终于实现了自己想要的效果,就是通过docker-compose 部署最新的mongodb replicaSet, 主要是为了测试 4.2 最新的多文档事务,下面将整个步骤分享一下:

docker-compose.yml 内容如下:

version: '3.4'

services:
    mongo:
        container_name: mongodb
        image: mongo:latest
        hostname: mongodb
        volumes:
          - /data/mongodb/mongod.conf:/etc/mongod.conf
          - /data/mongodb/data/db/:/data/db/
          - /data/mongodb/data/log/:/var/log/mongodb/
          - /data/mongodb/initdb.d/:/docker-entrypoint-initdb.d/
        environment:
          - MONGO_INITDB_ROOT_USERNAME=root
          - MONGO_INITDB_ROOT_PASSWORD=123456
        ports:
            - "27017:27017"
        healthcheck:
            test: test $$(echo "rs.initiate().ok || rs.status().ok" | mongo -u root -p '123456' --quiet) -eq 1
            interval: 10s
            start_period: 30s
        command: ["--replSet", "rs0", "--bind_ip_all"]

  

说明:

1、 /data/mongodb/mongod.conf  文件需要提前建好,内容如下,主要是启用验证,如果不挂载这个文件,replicaset 是在裸奔的

     

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /data/db
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled

#operationProfiling:

#replication:

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

  

2、 /data/mongodb/initdb.d  此目录下的脚本是用来初始化的,前提是没有任何数据前执行,我在该目录下创建了create-app-user.sh 来初始化自定义数据库【yourdb】以及用户名【yourAdmin】密码【123456】,内容如下:

#!/usr/bin/env bash
echo "Creating mongo users..."

mongo admin -u root -p 123456 << EOF
db.createUser({user: 'admin', pwd: '123456', roles: [{role: 'userAdminAnyDatabase', db: 'admin'}]});
db.grantRolesToUser(
   "admin",
   [ "clusterAdmin" ]
);
EOF

mongo admin -u admin -p 123456 << EOF
use yourdb
db.createUser({user: 'yourdbAdmin', pwd: '123456', roles:[{role:'readWrite',db:'yourdb'}]})
EOF
echo "Mongo users created for yourdb."

 

3、可以用monog client 测试登录:

   

mongo -u root -p 123456

 登录成功后,是这个样子滴:

执行 show dbs; 可以看到自己建了的数据库,测试自己建了的用户和密码,可以使用:

mongo -u yourdbAdmin -p 123456 --authenticationDatabase yourdb

  

 

posted @ 2019-08-21 18:37  AutoHome7390  阅读(394)  评论(0编辑  收藏