Files

69 lines
1.8 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: 使用 Docker 部署 MongoDB
createTime: 2025/12/24 16:34:00
permalink: /ops/docker/db/mongodb/
---
本教程将介绍如何使用 Docker 快速部署一个 MongoDB 实例。
## 在 Ubuntu 上部署 MongoDB:4.2 实例
我们先拉取 MongoDB:4.2 镜像:
```bash
docker pull mongo:4.2
```
创建一个目录用于存储 MongoDB 数据:
```bash
mkdir -p /data/mongo/
```
启动 MongoDB 容器:
```bash :wrap
sudo docker run --restart=always -itd --name mongo -p 27018:27017 -v /data/mongo/:/data/db mongo:4.2 --auth
```
命令详解:
- `--restart=always`:容器重启时自动启动。
- `-itd`:交互式模式运行容器,后台模式。
- `--name mongo`:为容器命名为 mongo。
- `-p 27018:27017`:将主机的 27018 端口映射到容器的 27017 端口。
- `-v /data/mongo/:/data/db`:将主机的 /data/mongo/ 目录挂载到容器的 /data/db 目录,用于持久化存储数据。
- `mongo:4.2`:使用 MongoDB:4.2 镜像。
- `--auth`:启用身份验证功能。
进入 MongoDB 容器:
```bash
docker exec -it mongo mongo admin
```
### 在 MongoDB 容器中创建管理员用户
先进入 admin 数据库
```bash
use admin;
```
创建管理员用户 admin, 密码 root, 角色为 root。
```bash
db.createUser( { user: "root", pwd: "root", roles:['root'] });
```
退出 MongoDB 容器:
```bash
exit
```
使用 root 用户进行登录
```bash
docker exec -it mongo mongo admin -u root -p root
```
这里还能创建一个 admin 用户,用密码 admin角色为 readWriteAnyDatabase, dbAdminAnyDatabase。
```bash
db.createUser( { user: "admin", pwd: "admin", roles:['readWriteAnyDatabase','dbAdminAnyDatabase'] } );
```
验证用户,这里会登录到 admin
```bash
db.auth("admin","admin");
```
删除用户的话可以使用,注意这里要切换回 root 用户
```bash
db.dropUser("admin");
```