咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

11、Docker-部署MongoDB

【hub.docker.com/mongo】

编写mongod配置文件

创建一个配置文件 /opt/my_mongo/config/mongod.conf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$ vim /opt/my_mongo/config/mongod.conf

storage:
dbPath: /var/lib/mongodb
journal:
enabled: true
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log

net:
port: 27017
# 主要是修改这里,允许远程连接
bindIp: 0.0.0.0

processManagement:
timeZoneInfo: /usr/share/zoneinfo

编写docker-compose.yml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
version: '3.3'
services:
my_mongo:
environment:
TZ: Asia/Shanghai
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123456
image: mongo:5.0.5
restart: always
ports:
- 27017:27017
volumes:
- /opt/my_mongo/db:/data/db
- /opt/my_mongo/config/mongod.conf:/etc/mongod.conf
- /opt/my_mongo/log:/var/log/mongodb
command: [--auth]
container_name: my_mongo_container
mongo-express:
image: mongo-express
restart: always
ports:
- 8081:8081
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: 123456
ME_CONFIG_MONGODB_URL: mongodb://root:123456@mongo:27017/
container_name: my_mongo_express_container

启动容器

1
$ docker-compose up

浏览器访问:http://IP:8081 可以访问 mongo-express web版界面管理mongo。

创建数据库

进入容器的bash环境创建数据库 test 和它的连接用户testuser:123456

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
$ docker exec -it my_mongo_container /bin/bash
$ mongo
> use admin
switched to db admin
>
> db.auth("root","123456")
1
>
> use test
switched to db test
>

# 创建只访问test数据库的用户
# 连接数据的链接: mongodb://testuser:123456@IP:27017/test
> db.createUser({ user:'testuser',pwd:'123456',roles:[ { role:'dbOwner', db: 'test'}]});
Successfully added user: {
"user" : "testuser",
"roles" : [
{
"role" : "dbOwner",
"db" : "test"
}
]
}
>
>
>
# 或者创建admin权限的用户
> db.createUser({user: "admin",pwd: "123456",roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]});
>

初始化脚本

创建容器都要进入bash创建数据很麻烦,如果容器数量多更加不是一个好的选择?解决的办法是创建一个脚本,在容器被创建的完成后执行这个脚本,实现创建数据库和用户就可以了。

mongo-init.sh

1
2
3
4
5
6
7
8
9
10
11
12
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
db = db.getSiblingDB('admin')
db.auth('$MONGO_INITDB_ROOT_USERNAME', '$MONGO_INITDB_ROOT_PASSWORD')
db = db.getSiblingDB('$MONGO_INITDB_DATABASE')
db.createUser({
user: "$MONGO_TEST_USERNAME",
pwd: "$MONGO_TEST_PASSWORD",
roles: [
{ role: 'dbOwner', db: '$MONGO_INITDB_DATABASE' }
]
})
EOF

编写 docker-compose.yml 文件 (简洁版)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
version: '3.3'
services:
my_mongo:
environment:
TZ: Asia/Shanghai
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: 123456
# 以下是自定义参数,给初始化脚本使用的
MONGO_INITDB_DATABASE: testdb
MONGO_TEST_USERNAME: test
MONGO_TEST_PASSWORD: 123456
image: mongo:5.0.5
restart: always
ports:
- 27017:27017
volumes:
# 执行初始化脚本
- ./mongo-init.sh:/docker-entrypoint-initdb.d/mongo-init.sh
command: [--auth]
container_name: my_test_mongo_container