1. 创建主机挂载配置目录

mkdir -p /root/i/docker/mongodb/data && cd /root/i/docker/mongodb

data目录存放mongodb数据库文件,删除重启容器不会丢失

2. 生成启动文件

2.1 无账户密码,不需要认证
cat <<EOF> start.sh
#!/bin/bash
MONGODB_DIR=`pwd`
docker stop mongodb
docker rm mongodb
docker run -d \\
  --name mongodb \\
  --restart always \\
  --privileged \\
  -p 27017:27017 \\
  -v \${MONGODB_DIR}/data:/data/db \\
  mongo:4.2.2
EOF
2.2 有账户密码,需要认证(推荐)
cat <<EOF> start.sh
#!/bin/bash
MONGODB_DIR=`pwd`
docker stop mongodb
docker rm mongodb
docker run -d \\
  --name mongodb \\
  --restart always \\
  --privileged \\
  -p 27017:27017 \\
  -v \${MONGODB_DIR}/data:/data/db \\
  -e MONGO_INITDB_ROOT_USERNAME=admin \\
  -e MONGO_INITDB_ROOT_PASSWORD=admin123 \\
  mongo:4.2.2 mongod --auth
EOF

说明:

  • -d: 后台运行容器;
  • --name: 指定容器名;
  • -p: 指定服务运行的端口;
  • -v: 映射目录或文件;
  • --privileged 拥有真正的root权限
  • --restart=always Docker服务重启容器也启动
  • -e MONGO_INITDB_ROOT_USERNAME=admin 指定用户名
  • -e MONGO_INITDB_ROOT_PASSWORD=admin123 指定密码
  • mongod --auth :容器默认启动命令是mongod,我们认证需要修改启动命为mongod --auth开启认证

3. 运行start.sh

sh start.sh

停止和删除容器

docker stop mongodb && docker rm mongodb

4. 使用Navicat连接

在这里插入图片描述
启动脚本配置不同,账号密码输入也不一样

  • 无账户密码用户名密码为空就能登录
  • 有账户密码:账号密码是上面设置的admin/admin123

点击测试连接
在这里插入图片描述

5. 进入容器

root@DESKTOP-NPQNVLA:~/i/docker/mongodb# docker exec -it mongodb bash
root@111eb14fb1e3:/# mongo --version
MongoDB shell version v4.2.2
git version: a0bbbff6ada159e19298d37946ac8dc4b497eadf
OpenSSL version: OpenSSL 1.1.1  11 Sep 2018
allocator: tcmalloc
modules: none
build environment:
    distmod: ubuntu1804
    distarch: x86_64
    target_arch: x86_64

6. 进入mongodb

6.1 无密码进入数据库
root@111eb14fb1e3:/# mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("62d25f54-4fc5-4127-923d-a43957798e3d") }
MongoDB server version: 4.2.2
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user

# 查看命令
> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, 'global' is default
        use <db_name>                set current database
        db.foo.find()                list objects in collection foo
        db.foo.find( { a : 1 } )     list objects in foo where a == 1
        it                           result of the last line evaluated; use to further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell
6.2 需要密码认证

在连接期间进行身份验证,使用-u <username>-p <password>--authenticationDatabase <database>命令行选项启动一个mongo shell

root@111eb14fb1e3:/# mongo --port 27017 -u "admin" -p "admin123" --authenticationDatabase "admin"
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4b2f16a9-63d0-4ea0-b534-f738ef37a162") }
MongoDB server version: 4.2.2
Server has startup warnings:
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten]
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten]
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
6.3 以 admin 用户身份进入
root@111eb14fb1e3:/# mongo --port 27017 -u "admin" -p "admin123" --authenticationDatabase "admin"
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?authSource=admin&compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4b2f16a9-63d0-4ea0-b534-f738ef37a162") }
MongoDB server version: 4.2.2
Server has startup warnings:
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten]
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2022-05-18T16:44:35.036+0000 I  STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten]
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2022-05-18T16:44:35.584+0000 I  CONTROL  [initandlisten]
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB
6.4 连接后验证

mongo shell 连接到 mongodb,也就是先连接,后验证用户身份

root@111eb14fb1e3:/# mongo
MongoDB shell version v4.2.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("a8d4a53b-bc0a-4dba-8bf6-a11fc62b2aa2") }
MongoDB server version: 4.2.2
> use admin
switched to db admin
> db.auth("admin", "admin123" )
1
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
test    0.000GB

7. 使用命令创建数据库

# 进入admin数据库
docker exec -it mongodb mongo admin

# 输入账号密码认证,返回1说明认证成功
> db.auth("admin", "admin123" )
1
# 查看所有数据库
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
# 创建新数据库
> use webflux
switched to db webflux
# 创建 和新创建的数据库 绑定的用户
> db.createUser({ user: 'wanfei', pwd: '123456', roles: [ { role: "readWrite", db: "webflux" } ] });
Successfully added user: {
	"user" : "wanfei",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "webflux"
		}
	]
}
# exit退出当前用户,否则继续认证新的用户会报错 too many users are authenticated
> exit
bye

# 进入 webflux 数据库
docker exec -it mongodb mongo webflux
# 重新认证新的用户
> db.auth("wanfei","123456")
1
# 随便添加一条信息才算创建成功
> db.webflux.insert({"name":"sss"});
WriteResult({ "nInserted" : 1 })
> show dbs
webflux  0.000GB

8. 使用命令删除用户

> use admin
switched to db admin
> db.auth("admin","xxxxxx")
1
# 创建一个root用户
> db.createUser({user: "root",pwd: "xxxxxx",roles: [ { role: "root", db: "admin" } ]})
> db.auth("root","xxxxxx")
> show users
{
	"_id" : "admin.admin",
	"user" : "admin",
	"db" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
{
	"_id" : "admin.root",
	"user" : "root",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
# 删除单个用户
> db.system.users.remove({user:"admin"})
WriteResult({ "nRemoved" : 1 })
> show users
{
	"_id" : "admin.root",
	"user" : "root",
	"db" : "admin",
	"roles" : [
		{
			"role" : "root",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐