美文网首页
MongoDB学习笔记(三)

MongoDB学习笔记(三)

作者: dev_winner | 来源:发表于2021-01-12 16:26 被阅读0次
    • 默认情况下,MongoDB实例启动运行时是没有启用用户访问权限控制的,也就是说,在实例本机服务器上都可以随意连接到实例进行各种操作,MongoDB不会对连接客户端进行用户验证,这是非常危险的。
    • mongodb官网上说,为了能保障mongodb的安全可以做以下几个步骤:
      • 使用新的端口,默认的27017端口,一旦知道了ip就能连接上,不太安全。
      • 设置mongodb的网络环境,最好将mongodb部署到公司服务器内网,这样外网是访问不到的,公司内部访问使用代理工具等。
      • 开启安全认证,既要设置服务器之间的内部认证方式,又要设置客户端连接到集群的账号密码认证方式。
    • 为了强制开启用户访问控制(用户验证),需要在MongoDB实例启动时使用选项--auth或在指定启动的配置文件中添加选项auth=true
    • 访问控制:MongoDB使用的是基于角色的访问控制(Role-Based Access Control,RBAC)来管理用户对实例的访问。通过对用户授予一个或多个角色来控制用户访问数据库资源的权限和数据库操作的权限,在对用户分配角色之前,用户无法访问实例。
    • 角色:在MongoDB中通过角色对用户授予相应数据库资源的操作权限,每个角色当中的权限可以显式指定,也可以通过继承其它角色的权限,或者两者都存在的权限。
    • 权限:由指定的数据库资源(resource)以及允许在指定资源上进行的操作(action)组成。
      • 资源(resource)包括:数据库、集合、部分集合和集群;
      • 操作(action)包括:对资源进行的增、删、改、查(CRUD)操作。
    • 在角色定义时可以包含一个或多个已存在的角色,新创建的角色会继承包含的角色中所有的权限。在同一个数据库中,新创建角色可以继承其它角色的权限,在 admin 数据库中创建的角色可以继承在其它任意数据库中角色的权限。
    • 常用的内置角色拥有的权限:
      • 数据库用户角色:readreadWrite
      • 所有数据库用户角色:readAnyDatabasereadWriteAnyDatabaseuserAdminAnyDatabasedbAdminAnyDatabase
      • 数据库管理角色:dbAdmindbOwneruserAdmin
      • 集群管理角色:clusterAdminclusterManagerclusterMonitor
        hostManager
      • 备份恢复角色:backuprestore
      • 超级用户角色:root
      • 内部角色:system
    权限 描述
    read 读取指定数据库中的任何数据
    readWrite 读写指定数据库中的任何数据,包括创建、重命名、删除集合
    readAnyDatabase 读取所有数据库中的任何数据(除了数据库config和local之外)
    readWriteAnyDatabase 读写所有数据库中的任何数据(除了数据库config和local之外)
    userAdminAnyDatabase 在指定数据库创建和修改用户(除了数据库config和local之外)
    dbAdminAnyDatabase 读取任何数据库以及对数据库进行清理、修改、压缩、获取统计信息、执行检查等操作(除了数据库config和local之外)
    dbAdmin 读取指定数据库以及对数据库进行清理、修改、压缩、获取统计信息、执行检查等操作
    userAdmin 在指定数据库创建和修改用户
    clusterAdmin 对整个集群或数据库系统进行管理操作
    backup 备份MongoDB数据最小的权限
    restore 从备份文件中还原恢复MongoDB数据(除了system.profile集合)的权限
    root 超级账号,超级权限
    • 对单实例(未开启副本集或分片)的MongoDB服务开启安全认证:
    • 按照普通无授权认证的配置来编写服务端的配置文件:vim /opt/mongodb/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27017
    
    • 按之前未开启认证的方式(不添加--auth参数)来启动MongoDB服务:
    [root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf 
    about to fork child process, waiting until server is ready for connections.
    forked process: 32072
    child process started successfully, parent exiting
    
    • 提示:在操作用户和启动mongod服务时尽量不要开启授权。
    • 登录Mongo客户端:/opt/mongodb/bin/mongo --port 27017
    • 创建两个管理员用户,一个是系统的超级管理员myroot,一个是admin库的管理用户myadmin
    > use admin
    switched to db admin
    > db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
    Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
    > db.createUser({user:"myadmin",pwd:"123456",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
    Successfully added user: {
        "user" : "myadmin",
        "roles" : [
            {
                "role" : "userAdminAnyDatabase",
                "db" : "admin"
            }
        ]
    }
    > db.system.users.find()  #查看已创建了的用户的情况
    { "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "zxV1hyvdbmi5RGwgx6lQHA==", "storedKey" : "WRCCuZl3jHCQo9z3nv0f028PJYs=", "serverKey" : "iX9+9kAcKfcmQjeyK2QxSKmEzvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "VBbrTSvxUWq+VS6qAeBWa7Vc+nMQ8IOCfkNmfg==", "storedKey" : "7yV5V/kF8ToxM6OOJVH4jFpUjsW6t1NHXwWBoEjLDxw=", "serverKey" : "+PP4GPcJ83SOd6O/CuxjqbRf2VMv4u+2yHAQf/gyjVE=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
    { "_id" : "admin.myadmin", "userId" : UUID("a7f5b9e9-cbb1-48c3-9020-cc83261ffe4d"), "user" : "myadmin", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "cSj5KAMm1cAD1YCQExTACg==", "storedKey" : "lh1ElhvOjc6dYu5yE0TWwM4POuI=", "serverKey" : "KzAg75OGyopuH2WjSFE43Lv0UXI=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "e8tcrQJcp2/+jdHI0p8oVT1gXrKlr3yLUKo65g==", "storedKey" : "b6c8RklClG8U2DXKsWJ9p6tdElhDesw/I6OyMk3alFk=", "serverKey" : "jlD+pal4tYh89vBJkgXc4i932xNv7TrIOsulyRzgOyU=" } }, "roles" : [ { "role" : "userAdminAnyDatabase", "db" : "admin" } ] }
    > db.dropUser("myadmin") #删除用户
    true
    > db.system.users.find()
    { "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "zxV1hyvdbmi5RGwgx6lQHA==", "storedKey" : "WRCCuZl3jHCQo9z3nv0f028PJYs=", "serverKey" : "iX9+9kAcKfcmQjeyK2QxSKmEzvo=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "VBbrTSvxUWq+VS6qAeBWa7Vc+nMQ8IOCfkNmfg==", "storedKey" : "7yV5V/kF8ToxM6OOJVH4jFpUjsW6t1NHXwWBoEjLDxw=", "serverKey" : "+PP4GPcJ83SOd6O/CuxjqbRf2VMv4u+2yHAQf/gyjVE=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
    > db.changeUserPassword("myroot", "123456") #修改密码
    
    • Mongodb中所有的用户信息都保存在admin数据库的集合system.users中,其保存用户名、密码和数据库信息。若不指定数据库,则创建指定权限的用户在所有数据库上都有效,如:{role:"userAdminAnyDatabase", db:""}
    • 测试添加的用户是否正确:
    > db.auth("myroot","12345")
    Error: Authentication failed.
    0
    > db.auth("myroot","123456")
    1
    
    • 创建普通用户既可以在没有开启认证时添加,也可以在开启认证之后添加,但开启认证之后,必须使用有操作admin库的用户登录认证后才能操作。
    > use articledb
    switched to db articledb
    > db.createUser({user: "bobo", pwd: "123456", roles: [{ role: "readWrite", db:"articledb" }]})
    Successfully added user: {
        "user" : "bobo",
        "roles" : [
            {
                "role" : "readWrite",
                "db" : "articledb"
            }
        ]
    }
    > db.auth("bobo","123456")
    1
    
    • 若开启认证后,则登录客户端的用户必须使用admin库的角色。如:拥有root角色的myadmin用户,再通过myadmin用户去创建其它角色的用户。
    • 关闭已启动的mongod服务,然后开启服务端认证:①在启动时指定参数-- auth/opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf --auth;②修改服务器配置文件:vim /opt/mongodb/conf/mongod.conf;③启动时不用加--auth参数:/opt/mongodb/bin/mongod -f /opt/mongodb/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27017
     security:
        authorization: enabled
    
    • 开启认证后使用mongo登录客户端:/opt/mongodb/bin/mongo --port 27017,执行该命令后发现打印的日志比较少了,原因:需要认证才可以进行下一步操作。
    > show dbs
    > use admin
    switched to db admin
    > show collections
    Warning: unable to run listCollections, attempting to approximate collection names by parsing connectionStatus
    > db.system.users.find()
    Error: error: {
        "ok" : 0,
        "errmsg" : "command find requires authentication",
        "code" : 13,
        "codeName" : "Unauthorized"
    }
    > db.auth("myroot","123456")
    1
    > db.system.users.find()
    { "_id" : "admin.myroot", "userId" : UUID("9c2dec75-971f-4407-9211-f03498a904fe"), "user" : "myroot", "db" : "admin", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "X2ugoiTtTxXo0y2VxUo70A==", "storedKey" : "CHV7inualEXuXcLLCKH/dCAeKhM=", "serverKey" : "AukG2aEGIeaoKCFwniaGGRJyP/A=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "qbd7wbnOdGq/cgF+rbpq9quQMM/mHzlLKkzGew==", "storedKey" : "1rHvt+DM5kAnAMvkD9KgIH/2YLxGLES32tg/rP0qpvI=", "serverKey" : "g1H4a9s+l6HQ6wUAsTWxsxBQZJWD3R2PmRjFGnHzsMo=" } }, "roles" : [ { "role" : "root", "db" : "admin" } ] }
    { "_id" : "articledb.bobo", "userId" : UUID("adad58df-b490-4f6e-9880-b85fd93d9778"), "user" : "bobo", "db" : "articledb", "credentials" : { "SCRAM-SHA-1" : { "iterationCount" : 10000, "salt" : "30mHAIGa3uG1nnbIrRAZgw==", "storedKey" : "HVfm1OKF4D4xZg+kDLNJiJOmxKo=", "serverKey" : "cqSEGV6NmADDcV8QhrTsz6zs8Nw=" }, "SCRAM-SHA-256" : { "iterationCount" : 15000, "salt" : "3UOrivatwuZk6jOXHMhmkIBzBDJfgoQh3umb8g==", "storedKey" : "Ad7s/dnsU9+bUNSBmkacO6Ct1fd+UPOfObnvTz+9o1E=", "serverKey" : "9msoX57PpWsK9hz8zOfEXD1U6mCX1Q79WufThQgSmck=" } }, "roles" : [ { "role" : "readWrite", "db" : "articledb" } ] }
    > show collections
    system.users
    system.version
    > exit
    bye
    --------------------------------------------------------------------------------------
    > use articledb
    switched to db articledb
    > db.auth("bobo","123456")
    1
    > show collections
    comment
    > show dbs
    articledb  0.000Gb
    
    使用Compass来认证登录
    • 在登录客户端时直接认证:/opt/mongodb/bin/mongo --port 27017 --authenticationDatabase admin -u myroot -p 123456或者/opt/mongodb/bin/mongo --port 27017 --authenticationDatabase articledb -u bobo -p 123456,其中-u:用户名;-p:密码;--authenticationDatabase:指定连接到哪个数据库。当登录是指定用户名和密码时,必须指定对应的数据库!
    • 对副本集执行访问控制需要配置两个方面:
      • 副本集和共享集群的各个节点之间使用内部身份验证,可以使用密钥文件或x.509证书。密钥文件比较简单,本文使用密钥文件,若是测试环境官方则推荐使用密钥文件;若是正式环境,官方则推荐x.509证书。原理:集群中每一个实例彼此连接时都检验彼此使用的证书内容是否相同。只有证书相同的实例彼此才可以互相访问。
      • 对于集群外部的访问,使用客户端连接到mongodb集群时,需要开启访问授权。
    • 副本集的每个mongod实例都使用keyfile的内容作为共享密码,只有具有正确密钥文件的mongod或者mongos实例才可以连接到副本集。密钥文件的内容必须在6到1024个字符之间,且在unix/linux系统中文件所有者必须有对文件至少有读的权限。
    • 启动副本集服务:
    [root@dev mongodb]# ps -ef | grep mongod
    root     32285 31928  0 16:52 pts/0    00:00:00 grep --color=auto mongod
    [root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 32288
    child process started successfully, parent exiting
    [root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 32367
    child process started successfully, parent exiting
    [root@dev mongodb]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 32449
    child process started successfully, parent exiting
    
    • 登录主节点并创建一个管理员账户:
    [root@dev mongodb]# /opt/mongodb/bin/mongo --port 27018
    myrs:PRIMARY> use admin
    switched to db admin
    myrs:PRIMARY> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
    Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
    
    • 创建副本集认证的key文件:使用openssl生成密码文件,然后使用chmod来更改文件权限,仅为文件所有者提供只读权限:
    [root@dev ~]# openssl rand -base64 90 -out ./mongo.keyfile
    [root@dev ~]# ll ./mongo.keyfile
    -rw-r--r-- 1 root root  122 Jan 13 17:03 mongo.keyfile
    [root@dev  ~]# chmod 400 ./mongo.keyfile
    [root@dev  ~]# ll ./mongo.keyfile
    -r-------- 1 root root  122 Jan 13 17:03 mongo.keyfile
    
    • 注意:副本集中每个节点都必须使用同一份keyfile,一般是在一台机器上生成,然后拷贝到其它机器上,且必须有只读权限。
    [root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27017/conf
    [root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27018/conf
    [root@dev ~]# cp ./mongo.keyfile /opt/mongodb/replica_sets/myrs_27019/conf
    [root@dev ~]# ll /opt/mongodb/replica_sets/myrs_27018/conf
    total 8
    -rw-r--r-- 1 root root 418 Jan 11 16:57 mongod.conf
    -r-------- 1 root root 122 Jan 13 17:08 mongo.keyfile
    
    • 修改副本集中各个节点的配置文件(指定keyfile的位置和开启安全认证):
    • vim /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/replica_sets/myrs_27017/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/replica_sets/myrs_27017/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/replica_sets/myrs_27017/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27017
     replication:
        replSetName: myrs
     security:
        keyFile: /opt/mongodb/replica_sets/myrs_27017/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/replica_sets/myrs_27018/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/replica_sets/myrs_27018/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/replica_sets/myrs_27018/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27018
     replication:
        replSetName: myrs
     security:
        keyFile: /opt/mongodb/replica_sets/myrs_27018/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/replica_sets/myrs_27019/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/replica_sets/myrs_27019/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/replica_sets/myrs_27019/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27019
     replication:
        replSetName: myrs
     security:
        keyFile: /opt/mongodb/replica_sets/myrs_27019/conf/mongo.keyfile
        authorization: enabled
    
    • 先关闭副本集进程号:kill -2 副本集中各个节点的进程号,再分别启动副本集节点:
    [root@dev ~]# ps -ef | grep mongod
    root     32616 31928  0 17:17 pts/0    00:00:00 grep --color=auto mongod
    [root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 32619
    child process started successfully, parent exiting
    [root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 32714
    child process started successfully, parent exiting
    [root@dev ~]# /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
    about to fork child process, waiting until server is ready for connections.
    forked process: 341
    child process started successfully, parent exiting
    [root@dev ~]# ps -ef | grep mongod
    root       341     1  2 17:18 ?        00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27019/conf/mongod.conf
    root       415 31928  0 17:19 pts/0    00:00:00 grep --color=auto mongod
    root     32619     1  2 17:18 ?        00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27017/conf/mongod.conf
    root     32714     1  2 17:18 ?        00:00:01 /opt/mongodb/bin/mongod -f /opt/mongodb/replica_sets/myrs_27018/conf/mongod.conf
    
    • 登录主节点客户端并添加一个普通账号:
    [root@dev ~]# /opt/mongodb/bin/mongo --port 27017
    myrs:PRIMARY> show dbs
    myrs:PRIMARY> use admin
    switched to db admin
    myrs:PRIMARY> db.auth("myroot","123456")
    1
    myrs:PRIMARY> show dbs
    admin      0.000GB
    articledb  0.000GB
    config     0.000GB
    local      0.001GB
    myrs:PRIMARY> use articledb
    switched to db articledb
    myrs:PRIMARY> db.createUser({user: "bobo", pwd: "123456", roles: ["readWrite"]})
    Successfully added user: { "user" : "bobo", "roles" : [ "readWrite" ] }
    
    • 分片集群环境下的安全认证和副本集环境下基本上一样,但分片集群的服务器环境和架构较为复杂,建议在搭建分片集群时,直接加入安全认证和服务器间的鉴权,若之前有数据,则先将之前的数据备份出来,再还原回去。
    • 依次kill mongos路由、配置副本集服务,分片副本集服务,主从节点直到所有成员都离线为止。在kill副本集时,建议先kill仲裁者,再kill副本节点,最后是主节点,以避免潜在的回滚。kill完要检查一下,避免有的没有被kill。
    • 创建副本集认证的key文件:使用openssl生成密码文件,然后使用chmod来更改文件权限,仅为文件所有者提供只读权限:
    [root@dev ~]# openssl rand -base64 90 -out ./mongo.keyfile
    [root@dev ~]# ll ./mongo.keyfile
    -rw-r--r-- 1 root root  122 Jan 13 17:03 mongo.keyfile
    [root@dev  ~]# chmod 400 ./mongo.keyfile
    [root@dev  ~]# ll ./mongo.keyfile
    -r-------- 1 root root  122 Jan 13 17:03 mongo.keyfile
    
    • 注意:副本集中每个节点都必须使用同一份keyfile,一般是在一台机器上生成,然后拷贝到其它机器上,且必须有只读权限。
    [root@dev ~]# echo '/opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile
    > /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile' | xargs -n 1 cp -v /root/mongo.keyfile
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile’
    ‘/root/mongo.keyfile’ -> ‘/opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile’
    
    • 修改副本集中各个节点的配置文件(指定keyfile的位置和开启安全认证):
    • vim /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs01_27018/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27018/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27018/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27018
     replication:
        replSetName: myshardrs01
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs01_27118/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27118/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27118/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27118
     replication:
        replSetName: myshardrs01
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs01_27218/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs01_27218/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs01_27218/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27218
     replication:
        replSetName: myshardrs01
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs02_27318/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27318/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27318/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27318
     replication:
        replSetName: myshardrs02
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs02_27418/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27418/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27418/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27418
     replication:
        replSetName: myshardrs02
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myshardrs02_27518/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myshardrs02_27518/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myshardrs02_27518/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27518
     replication:
        replSetName: myshardrs02
     sharding:
        clusterRole: shardsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myconfigrs_27019/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27019/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27019/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27019
     replication:
        replSetName: myconfigrs
     sharding:
        clusterRole: configsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myconfigrs_27119/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27119/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27119/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27119
     replication:
        replSetName: myconfigrs
     sharding:
        clusterRole: configsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongod.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/myconfigrs_27219/logs/mongod.log
        logAppend: true
     storage:
        dbPath: /opt/mongodb/sharded_cluster/myconfigrs_27219/data/db
        journal:
            enabled: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/myconfigrs_27219/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27219
     replication:
        replSetName: myconfigrs
     sharding:
        clusterRole: configsvr
     security:
        keyFile: /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongo.keyfile
        authorization: enabled
    
    • vim /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongos.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/mymongos_27017/logs/mongod.log
        logAppend: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/mymongos_27017/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27017
     sharding:
        configDB: myconfigrs/公网ip:27019,公网ip:27119,公网ip:27219
     security:
        keyFile: /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongo.keyfile
    
    • vim /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongos.conf
     systemLog:
        destination: file
        path: /opt/mongodb/sharded_cluster/mymongos_27117/logs/mongod.log
        logAppend: true
     processManagement:
        fork: true
        pidFilePath: /opt/mongodb/sharded_cluster/mymongos_27117/logs/mongod.pid
     net:
        bindIp: localhost,192.168.0.128
        port: 27117
     sharding:
        configDB: myconfigrs/公网ip:27019,公网ip:27119,公网ip:27219
     security:
        keyFile: /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile
    
    • mongos比mongod少了authorization: enabled的配置,原因:副本集加分片的安全认证需要配置两方面的,副本集中各个节点之间使用内部身份验证,用于内部各个mongo实例的通信,只有相同keyfile才能相互访问,所以都要开启keyFile: /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongo.keyfile。然而对于所有的mongod,才是真正保存数据的分片。mongos只做路由,不保存数据。所有的mongod开启访问数据的授权authorization: enabled,这样只有用户登录的账号密码正确才能访问到数据。
    • 必须依次启动配置节点、分片节点、路由节点,注意启动顺序:
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27019/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27119/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myconfigrs_27219/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27018/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27118/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs01_27218/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27318/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27418/conf/mongod.conf
    /opt/mongodb/bin/mongod -f /opt/mongodb/sharded_cluster/myshardrs02_27518/conf/mongod.conf
    /opt/mongodb/bin/mongos -f /opt/mongodb/sharded_cluster/mymongos_27017/conf/mongos.conf
    /opt/mongodb/bin/mongos -f /opt/mongodb/sharded_cluster/mymongos_27117/conf/mongos.conf
    
    • 通过localhost登录任意一个mongos路由,并创建一个管理员帐号和一个普通权限的帐号:
    [root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
    mongos> use admin
    switched to db admin
    mongos> db.createUser({user:"myroot",pwd:"123456",roles:["root"]})
    Successfully added user: { "user" : "myroot", "roles" : [ "root" ] }
    mongos> db.auth("myroot","123456")
    1
    mongos> db.createUser({user: "bobo", pwd: "123456", roles: [{ role: "readWrite",db: "articledb" }]})
    Successfully added user: {
        "user" : "bobo",
        "roles" : [
            {
                "role" : "readWrite",
                "db" : "articledb"
            }
        ]
    }
    mongos> db.auth("bobo","123456")
    1
    
    • 提示:通过mongos添加的账号信息,只会保存到配置节点的服务器中,具体的数据节点不保存账号信息,所以分片中的账号信息不涉及到同步问题。
    • 在mongo客户端登录mongos路由,用管理员帐号登录可查看分片情况:
    [root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
    mongos> use admin
    switched to db admin
    mongos> db.auth("myroot","123456")
    1
    mongos> sh.status()
    --- Sharding Status --- 
      sharding version: {
        "_id" : 1,
        "minCompatibleVersion" : 5,
        "currentVersion" : 6,
        "clusterId" : ObjectId("5ffd13a86c140163a85aa531")
      }
      shards:
            {  "_id" : "myshardrs01",  "host" : "myshardrs01/公网ip:27018,公网ip:27118",  "state" : 1 }
            {  "_id" : "myshardrs02",  "host" : "myshardrs02/公网ip:27318,公网ip:27418",  "state" : 1 }
      active mongoses:
            "4.4.3" : 2
      autosplit:
            Currently enabled: yes
      balancer:
            Currently enabled:  yes
            Currently running:  no
            Failed balancer rounds in last 5 attempts:  2
            Last reported error:  Could not find host matching read preference { mode: "primary" } for set myshardrs02
            Time of Reported error:  Wed Jan 13 2021 22:44:38 GMT+0800 (CST)
            Migration Results for the last 24 hours: 
                    No recent migrations
      databases:
            {  "_id" : "articledb",  "primary" : "myshardrs02",  "partitioned" : true,  "version" : {  "uuid" : UUID("03cc6699-146c-46f3-b266-5f43b8d65a39"),  "lastMod" : 1 } }
                    articledb.author
                            shard key: { "age" : 1 }
                            unique: false
                            balancing: true
                            chunks:
                                    myshardrs01 2
                                    myshardrs02 2
                            { "age" : { "$minKey" : 1 } } -->> { "age" : 0 } on : myshardrs01 Timestamp(2, 0) 
                            { "age" : 0 } -->> { "age" : 49 } on : myshardrs02 Timestamp(3, 1) 
                            { "age" : 49 } -->> { "age" : 119 } on : myshardrs02 Timestamp(2, 3) 
                            { "age" : 119 } -->> { "age" : { "$maxKey" : 1 } } on : myshardrs01 Timestamp(3, 0) 
                    articledb.comment
                            shard key: { "nickname" : "hashed" }
                            unique: false
                            balancing: true
                            chunks:
                                    myshardrs01 2
                                    myshardrs02 2
                            { "nickname" : { "$minKey" : 1 } } -->> { "nickname" : NumberLong("-4611686018427387902") } on : myshardrs01 Timestamp(1, 0) 
                            { "nickname" : NumberLong("-4611686018427387902") } -->> { "nickname" : NumberLong(0) } on : myshardrs01 Timestamp(1, 1) 
                            { "nickname" : NumberLong(0) } -->> { "nickname" : NumberLong("4611686018427387902") } on : myshardrs02 Timestamp(1, 2) 
                            { "nickname" : NumberLong("4611686018427387902") } -->> { "nickname" : { "$maxKey" : 1 } } on : myshardrs02 Timestamp(1, 3) 
            {  "_id" : "config",  "primary" : "config",  "partitioned" : true }
                    config.system.sessions
                            shard key: { "_id" : 1 }
                            unique: false
                            balancing: true
                            chunks:
                                    myshardrs01 512
                                    myshardrs02 512
                            too many chunks to print, use verbose if you want to force print
    
    • 退出连接,重新连接服务,使用普通权限帐号访问数据:
    [root@dev mongodb]# /opt/mongodb/bin/mongo --port 27017
    mongos> use articledb
    switched to db articledb
    mongos> db.auth("bobo","123456")
    1
    mongos> show collections
    author
    comment
    mongos> db.comment.count()
    1000
    

    相关文章

      网友评论

          本文标题:MongoDB学习笔记(三)

          本文链接:https://www.haomeiwen.com/subject/uskeaktx.html