文档帮你翻译好了,让你一站式上手MongoDB
MongoDB 的设计理念和基本架构:
- MongoDB 是什么?
简单理解:
- 一个存储数据的数据库
- 数据格式像 JSON
- 不需要固定的表结构
- 容易扩展和维护
类比:
- 传统数据库像精心设计的档案柜
- MongoDB 像自由组合的收纳盒
- 核心概念对比
MySQL MongoDB
数据库(Database) 数据库(Database)
表(Table) 集合(Collection)
行(Row) 文档(Document)
列(Column) 字段(Field)
例如:
MySQL:
| id | name | age |
| 1 | 张三 | 20 |
MongoDB:
{
"_id": 1,
"name": "张三",
"age": 20
}
- 基本架构
客户端层:
- 应用程序
- MongoDB Shell
- 管理工具
服务器层:
- mongod (数据库服务)
- mongos (路由服务,分片时使用)
存储层:
- 数据文件
- 索引文件
- 数据存储示例
// 创建/选择数据库
use mydb
// 插入数据
db.users.insertOne({
name: "张三",
age: 20,
hobbies: ["读书", "运动"],
address: {
city: "北京",
street: "朝阳路"
}
})
- 基本操作
// 查找
db.users.find({name: "张三"})
// 更新
db.users.updateOne(
{name: "张三"},
{$set: {age: 21}}
)
// 删除
db.users.deleteOne({name: "张三"})
- 特点优势
灵活性:
- 不需要预定义结构
- 可以随时添加字段
- 支持复杂数据类型
扩展性:
- 容易水平扩展
- 支持大数据量
- 高性能读写
易用性:
- 直观的数据格式
- 简单的查询语法
- 丰富的功能支持
- 适用场景
适合:
- 需求经常变化的项目
- 数据结构不固定
- 大数据量应用
- 快速开发原型
不太适合:
- 需要复杂事务
- 强关系型数据
- 需要联表查询多的场景
- 简单示例应用
// 博客文章存储
{
"_id": ObjectId("..."),
"title": "MongoDB入门",
"content": "MongoDB是一个文档数据库...",
"author": {
"name": "张三",
"email": "[email protected]"
},
"tags": ["数据库", "NoSQL"],
"comments": [
{
"user": "李四",
"content": "写得很好"
}
]
}
- 基本工具
命令行工具:
- mongo shell (交互式命令行)
- mongosh (新版命令行工具)
图形界面:
- MongoDB Compass (官方工具)
- Studio 3T (第三方工具)
- 简单部署
# 启动服务器
mongod --dbpath /data/db
# 连接数据库
mongo
# 检查状态
db.serverStatus()
- 常用概念
文档(Document):
- MongoDB 中的基本数据单元
- 类似 JSON 格式
集合(Collection):
- 文档的集合
- 类似关系数据库的表
数据库(Database):
- 集合的集合
- 独立的命名空间
全面解析
- 基本概念
// 数据结构层级
database → collection → document → field
// 文档示例
{
_id: ObjectId("5099803df3f4948bd2f98391"),
name: "张三",
age: 20,
address: {
city: "北京",
street: "朝阳路"
},
hobbies: ["读书", "音乐"]
}
- CRUD操作
// 创建
db.users.insertOne({
name: "张三",
age: 20
})
// 查询
db.users.find({
age: {$gt: 18}
}).sort({name: 1})
// 更新
db.users.updateOne(
{name: "张三"},
{$set: {age: 21}}
)
// 删除
db.users.deleteOne({
name: "张三"
})
- 索引管理
// 创建索引
db.users.createIndex({name: 1}) // 升序
db.users.createIndex({age: -1}) // 降序
// 复合索引
db.users.createIndex({name: 1, age: -1})
// 唯一索引
db.users.createIndex(
{email: 1},
{unique: true}
)
// 查看索引
db.users.getIndexes()
- 聚合操作
db.orders.aggregate([
// 过滤
{$match: {status: "completed"}},
// 分组
{$group: {
_id: "$userId",
total: {$sum: "$amount"},
count: {$sum: 1}
}},
// 排序
{$sort: {total: -1}},
// 限制
{$limit: 10}
])
- 数据模型设计
// 1. 内嵌文档(一对一)
{
_id: 1,
item: "xyz",
specs: {
color: "red",
size: 10
}
}
// 2. 数组引用(一对多)
{
_id: 1,
item: "xyz",
tags: ["A", "B", "C"]
}
// 3. 引用关系(多对多)
{
_id: 1,
name: "张三",
friends: [ObjectId("..."), ObjectId("...")]
}
- 事务支持
// 开启事务
session.startTransaction()
try {
db.accounts.updateOne(
{_id: fromId},
{$inc: {balance: -100}}
)
db.accounts.updateOne(
{_id: toId},
{$inc: {balance: 100}}
)
session.commitTransaction()
} catch (error) {
session.abortTransaction()
}
- 分片集群
// 分片配置
sh.enableSharding("mydb")
sh.shardCollection("mydb.users", {_id: "hashed"})
// 分片键选择
{
// 范围分片
sh.shardCollection("mydb.logs", {timestamp: 1})
// 哈希分片
sh.shardCollection("mydb.users", {userId: "hashed"})
}
- 副本集配置
// 初始化副本集
rs.initiate({
_id: "rs0",
members: [
{_id: 0, host: "mongodb0.example.net:27017"},
{_id: 1, host: "mongodb1.example.net:27017"},
{_id: 2, host: "mongodb2.example.net:27017"}
]
})
// 查看状态
rs.status()
- 性能优化
// 1. 索引优化
db.users.explain("executionStats").find({age: {$gt: 20}})
// 2. 查询优化
db.users.find({age: {$gt: 20}}).hint({age: 1})
// 3. 投影优化
db.users.find({}, {name: 1, age: 1})
- 监控和诊断
// 系统状态
db.serverStatus()
// 性能统计
db.stats()
// 慢查询分析
db.setProfilingLevel(1, {slowms: 100})
db.system.profile.find()
- 安全配置
// 创建用户
db.createUser({
user: "admin",
pwd: "password",
roles: ["root"]
})
// 启用认证
mongod --auth
// 角色管理
db.grantRolesToUser("admin", ["readWrite"])
- 备份恢复
# 备份
mongodump --db mydb --out /backup
# 恢复
mongorestore --db mydb /backup/mydb
# 导出集合
mongoexport --db mydb --collection users --out users.json
# 导入集合
mongoimport --db mydb --collection users --file users.json
- Java集成示例
@Document(collection = "users")
public class User {
@Id
private String id;
private String name;
private Integer age;
@DBRef
private List<Order> orders;
}
@Repository
public interface UserRepository
extends MongoRepository<User, String> {
List<User> findByAgeBetween(int start, int end);
@Query("{'name': ?0}")
User findByCustomQuery(String name);
}
- 地理空间索引和查询
// 创建2d索引
db.places.createIndex({location: "2d"})
// 创建2dsphere索引
db.places.createIndex({location: "2dsphere"})
// 近距离查询
db.places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [longitude, latitude]
},
$maxDistance: 1000 // 米
}
}
})
// 区域查询
db.places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [[[lng1,lat1], [lng2,lat2], ...]]
}
}
}
})
- 全文搜索
// 创建文本索引
db.articles.createIndex({
title: "text",
content: "text"
})
// 全文搜索
db.articles.find({
$text: {
$search: "mongodb nosql",
$language: "english"
}
})
// 相关度排序
db.articles.find(
{$text: {$search: "mongodb"}},
{score: {$meta: "textScore"}}
).sort({score: {$meta: "textScore"}})
- Change Streams
// 监听集合变更
const changeStream = db.collection('users').watch();
changeStream.on('change', (change) => {
console.log(change); // 插入、更新、删除事件
});
// 带过滤器的变更流
const pipeline = [
{$match: {'fullDocument.status': 'active'}}
];
const filteredStream = db.collection('users').watch(pipeline);
- 数据压缩和存储
// 创建带压缩的集合
db.createCollection("logs", {
storageEngine: {
wiredTiger: {
configString: "block_compressor=zlib"
}
}
})
// 查看存储统计
db.collection.stats()
// 压缩比例
db.serverStatus().wiredTiger.block-manager
- GridFS文件存储
// 存储文件
const bucket = new GridFSBucket(db);
fs.createReadStream('video.mp4')
.pipe(bucket.openUploadStream('video.mp4'));
// 读取文件
bucket.openDownloadStreamByName('video.mp4')
.pipe(fs.createWriteStream('video-copy.mp4'));
// 查找文件
db.fs.files.find({filename: 'video.mp4'})
- 时序数据处理
// 创建时序集合
db.createCollection("metrics", {
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "hours"
}
})
// 插入数据
db.metrics.insertOne({
timestamp: new Date(),
metadata: {sensor: "A1"},
value: 42
})
// 时序聚合
db.metrics.aggregate([
{
$group: {
_id: {
sensor: "$metadata.sensor",
hour: {$hour: "$timestamp"}
},
avgValue: {$avg: "$value"}
}
}
])
- 高级聚合操作
// 聚合管道阶段
db.orders.aggregate([
// $lookup (JOIN)
{
$lookup: {
from: "users",
localField: "userId",
foreignField: "_id",
as: "userInfo"
}
},
// $unwind (展开数组)
{$unwind: "$userInfo"},
// $project (投影)
{
$project: {
orderNo: 1,
userName: "$userInfo.name",
total: {$multiply: ["$quantity", "$price"]}
}
},
// $facet (多面分析)
{
$facet: {
"byCategory": [{$group: {_id: "$category"}}],
"byStatus": [{$group: {_id: "$status"}}]
}
}
])
- 分布式锁实现
// 获取锁
function acquireLock(lockName, timeout) {
return db.locks.findOneAndUpdate(
{
_id: lockName,
lockedAt: {$lt: new Date(Date.now() - timeout)}
},
{
$set: {
lockedAt: new Date(),
owner: process.pid
}
},
{upsert: true}
);
}
// 释放锁
function releaseLock(lockName) {
return db.locks.deleteOne({
_id: lockName,
owner: process.pid
});
}
- 性能诊断工具
// 执行计划分析
db.users.explain("executionStats").find({
age: {$gt: 20},
city: "Beijing"
})
// 索引使用情况
db.users.aggregate([
{$indexStats: {}}
])
// 慢查询分析
db.setProfilingLevel(2)
db.system.profile.find().sort({millis:-1})
- 运维管理脚本
// 监控脚本
function monitorDB() {
const stats = db.serverStatus();
const metrics = {
connections: stats.connections.current,
opcounters: stats.opcounters,
memory: stats.mem,
replication: rs.status()
};
db.monitoring.insertOne({
timestamp: new Date(),
metrics: metrics
});
}
// 清理脚本
function cleanup() {
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
db.logs.deleteMany({
createdAt: {$lt: thirtyDaysAgo}
});
}
关键建议:
- 合理使用高级特性
- 注意性能影响
- 做好监控和维护
- 定期优化和清理
- 保证数据安全性
MongoDB的这些高级特性能够帮助:
- 处理复杂业务需求
- 提升系统性能
- 简化运维管理
- 保障数据安全
如何部署运维mongodb
这是我写的一个完整的MongoDB安装配置运维脚本(原生裸机):
- 下载安装脚本(install_mongodb.sh)
#!/bin/bash
# 变量定义
MONGODB_VERSION="6.0"
INSTALL_DIR="/opt/mongodb"
DATA_DIR="/data/mongodb"
LOG_DIR="/var/log/mongodb"
CONFIG_DIR="/etc/mongodb"
# 创建用户和目录
create_dirs() {
echo "Creating mongodb user and directories..."
useradd -r -s /sbin/nologin mongodb
mkdir -p $INSTALL_DIR
mkdir -p $DATA_DIR
mkdir -p $LOG_DIR
mkdir -p $CONFIG_DIR
chown -R mongodb:mongodb $DATA_DIR
chown -R mongodb:mongodb $LOG_DIR
}
# 下载并安装MongoDB
install_mongodb() {
echo "Installing MongoDB..."
# CentOS/RHEL
if [ -f /etc/redhat-release ]; then
cat > /etc/yum.repos.d/mongodb-org.repo <<EOF
[mongodb-org-${MONGODB_VERSION}]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/\$releasever/mongodb-org/${MONGODB_VERSION}/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-${MONGODB_VERSION}.asc
EOF
yum install -y mongodb-org
# Ubuntu
elif [ -f /etc/lsb-release ]; then
wget -qO - https://www.mongodb.org/static/pgp/server-${MONGODB_VERSION}.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/${MONGODB_VERSION} multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-${MONGODB_VERSION}.list
apt-get update
apt-get install -y mongodb-org
fi
}
- 配置文件(mongodb.conf)
# 创建配置文件
create_config() {
cat > $CONFIG_DIR/mongodb.conf <<EOF
# 系统配置
systemLog:
destination: file
path: ${LOG_DIR}/mongod.log
logAppend: true
# 存储配置
storage:
dbPath: ${DATA_DIR}
journal:
enabled: true
engine: wiredTiger
wiredTiger:
engineConfig:
cacheSizeGB: 1
# 进程控制
processManagement:
fork: true
pidFilePath: /var/run/mongodb/mongod.pid
# 网络配置
net:
port: 27017
bindIp: 127.0.0.1
# 安全配置
security:
authorization: enabled
EOF
}
- 系统服务配置(mongodb.service)
# 创建系统服务
create_service() {
cat > /etc/systemd/system/mongodb.service <<EOF
[Unit]
Description=MongoDB Database Server
Documentation=https://docs.mongodb.org/manual
After=network.target
[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --config ${CONFIG_DIR}/mongodb.conf
ExecStop=/usr/bin/mongod --config ${CONFIG_DIR}/mongodb.conf --shutdown
PIDFile=/var/run/mongodb/mongod.pid
Type=forking
[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
}
- 初始化脚本(init_mongodb.js)
// 创建管理员用户
create_admin_user() {
cat > init_mongodb.js <<EOF
db.createUser({
user: "admin",
pwd: "your_password_here",
roles: ["root"]
})
EOF
mongosh admin init_mongodb.js
}
- 监控脚本(monitor_mongodb.sh)
#!/bin/bash
# 监控MongoDB状态
monitor_mongodb() {
# 检查进程
if ! pgrep mongod > /dev/null; then
echo "MongoDB is not running!"
exit 1
}
# 检查连接数
connections=$(mongosh admin --eval "db.serverStatus().connections.current" --quiet)
echo "Current connections: $connections"
# 检查存储空间
disk_usage=$(du -sh $DATA_DIR)
echo "Disk usage: $disk_usage"
# 检查日志错误
errors=$(tail -n 1000 $LOG_DIR/mongod.log | grep -i "error" | wc -l)
echo "Error count in recent logs: $errors"
}
- 备份脚本(backup_mongodb.sh)
#!/bin/bash
# 备份配置
BACKUP_DIR="/backup/mongodb"
RETENTION_DAYS=7
# 执行备份
backup_mongodb() {
DATE=$(date +%Y%m%d)
BACKUP_PATH="${BACKUP_DIR}/${DATE}"
# 创建备份目录
mkdir -p $BACKUP_PATH
# 执行备份
mongodump --out $BACKUP_PATH
# 压缩备份
cd $BACKUP_DIR
tar czf "${DATE}.tar.gz" $DATE
rm -rf $DATE
# 删除旧备份
find $BACKUP_DIR -name "*.tar.gz" -mtime +$RETENTION_DAYS -delete
}
- 主函数(main)
main() {
# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
echo "Please run as root"
exit 1
}
# 执行安装步骤
create_dirs
install_mongodb
create_config
create_service
# 启动服务
systemctl start mongodb
systemctl enable mongodb
# 创建管理员用户
create_admin_user
echo "MongoDB installation completed!"
}
# 执行主函数
main
- 使用说明
# 安装
chmod +x install_mongodb.sh
./install_mongodb.sh
# 监控
chmod +x monitor_mongodb.sh
./monitor_mongodb.sh
# 备份
chmod +x backup_mongodb.sh
./backup_mongodb.sh
- 常用维护命令
# 启动服务
systemctl start mongodb
# 停止服务
systemctl stop mongodb
# 重启服务
systemctl restart mongodb
# 查看状态
systemctl status mongodb
# 查看日志
tail -f /var/log/mongodb/mongod.log
- 注意事项
# 安全配置
- 修改默认端口
- 设置强密码
- 限制网络访问
- 定期更新版本
# 性能优化
- 适当配置缓存大小
- 监控系统资源
- 定期清理日志
- 优化索引使用
# 运维建议
- 定期备份数据
- 监控系统状态
- 及时处理告警
- 保持日志清晰
使用这些脚本可以:
- 快速部署MongoDB
- 自动化日常维护
- 保障系统安全
- 简化运维工作
让我提供一个完整的MongoDB在K8s上的部署配置和运维方案:
- 命名空间配置(namespace.yaml)
apiVersion: v1
kind: Namespace
metadata:
name: mongodb
- 配置文件(configmap.yaml)
apiVersion: v1
kind: ConfigMap
metadata:
name: mongodb-config
namespace: mongodb
data:
mongod.conf: |
storage:
dbPath: /data/db
journal:
enabled: true
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 0.0.0.0
replication:
replSetName: "rs0"
security:
authorization: enabled
- 密钥配置(secret.yaml)
apiVersion: v1
kind: Secret
metadata:
name: mongodb-secret
namespace: mongodb
type: Opaque
data:
# echo -n 'admin' | base64
MONGO_ROOT_USERNAME: YWRtaW4=
# echo -n 'password' | base64
MONGO_ROOT_PASSWORD: cGFzc3dvcmQ=
- 持久化存储(pvc.yaml)
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: mongodb-data
namespace: mongodb
spec:
accessModes:
- ReadWriteOnce
resources:
requests:
storage: 10Gi
storageClassName: standard
- StatefulSet配置(statefulset.yaml)
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb
namespace: mongodb
spec:
serviceName: mongodb
replicas: 3
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo:6.0
ports:
- containerPort: 27017
env:
- name: MONGO_INITDB_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_USERNAME
- name: MONGO_INITDB_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_PASSWORD
volumeMounts:
- name: mongodb-data
mountPath: /data/db
- name: mongodb-config
mountPath: /etc/mongo
resources:
requests:
memory: "1Gi"
cpu: "0.5"
limits:
memory: "2Gi"
cpu: "1"
livenessProbe:
exec:
command:
- mongo
- --eval
- "db.adminCommand('ping')"
initialDelaySeconds: 30
periodSeconds: 10
readinessProbe:
exec:
command:
- mongo
- --eval
- "db.adminCommand('ping')"
initialDelaySeconds: 5
periodSeconds: 10
volumes:
- name: mongodb-config
configMap:
name: mongodb-config
- 服务配置(service.yaml)
apiVersion: v1
kind: Service
metadata:
name: mongodb
namespace: mongodb
spec:
selector:
app: mongodb
ports:
- port: 27017
targetPort: 27017
clusterIP: None
- 初始化脚本(init-configmap.yaml)
apiVersion: v1
kind: ConfigMap
metadata:
name: mongo-init
namespace: mongodb
data:
init.js: |
rs.initiate({
_id: "rs0",
members: [
{ _id: 0, host: "mongodb-0.mongodb:27017" },
{ _id: 1, host: "mongodb-1.mongodb:27017" },
{ _id: 2, host: "mongodb-2.mongodb:27017" }
]
})
- 监控配置(servicemonitor.yaml)
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: mongodb-monitor
namespace: mongodb
spec:
selector:
matchLabels:
app: mongodb
endpoints:
- port: mongodb
interval: 30s
- 部署脚本(deploy.sh)
#!/bin/bash
# 创建命名空间和基础资源
kubectl apply -f namespace.yaml
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
kubectl apply -f pvc.yaml
# 部署MongoDB
kubectl apply -f statefulset.yaml
kubectl apply -f service.yaml
# 等待Pod就绪
kubectl wait --for=condition=ready pod -l app=mongodb -n mongodb --timeout=300s
# 初始化复制集
kubectl apply -f init-configmap.yaml
kubectl exec -it mongodb-0 -n mongodb -- mongo --eval "$(cat init.js)"
# 部署监控
kubectl apply -f servicemonitor.yaml
- 备份脚本(backup-cronjob.yaml)
apiVersion: batch/v1beta1
kind: CronJob
metadata:
name: mongodb-backup
namespace: mongodb
spec:
schedule: "0 2 * * *"
jobTemplate:
spec:
template:
spec:
containers:
- name: backup
image: mongo:6.0
command:
- /bin/sh
- -c
- |
mongodump --host=mongodb-0.mongodb \
--username=$MONGO_ROOT_USERNAME \
--password=$MONGO_ROOT_PASSWORD \
--out=/backup/$(date +%Y%m%d)
env:
- name: MONGO_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_USERNAME
- name: MONGO_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_PASSWORD
volumeMounts:
- name: backup
mountPath: /backup
volumes:
- name: backup
persistentVolumeClaim:
claimName: mongodb-backup
restartPolicy: OnFailure
- HPA配置(hpa.yaml)
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: mongodb-hpa
namespace: mongodb
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: StatefulSet
name: mongodb
minReplicas: 3
maxReplicas: 5
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 80
- 运维命令示例
# 查看Pod状态
kubectl get pods -n mongodb
# 查看日志
kubectl logs -f mongodb-0 -n mongodb
# 进入容器
kubectl exec -it mongodb-0 -n mongodb -- bash
# 扩展副本
kubectl scale statefulset mongodb -n mongodb --replicas=5
# 查看监控
kubectl port-forward svc/prometheus-operated -n monitoring 9090:9090
使用说明:
部署前准备: 确保有可用的K8s集群; 安装Helm (如果需要);配置存储类;准备镜像仓库
- 部署步骤
# 部署基础设施
kubectl apply -f namespace.yaml
kubectl apply -f configmap.yaml
kubectl apply -f secret.yaml
kubectl apply -f pvc.yaml
# 部署MongoDB
kubectl apply -f statefulset.yaml
kubectl apply -f service.yaml
# 初始化复制集
kubectl apply -f init-configmap.yaml
# 部署监控和备份
kubectl apply -f servicemonitor.yaml
kubectl apply -f backup-cronjob.yaml
kubectl apply -f hpa.yaml
- 故障恢复(recovery-job.yaml)
apiVersion: batch/v1
kind: Job
metadata:
name: mongodb-recovery
namespace: mongodb
spec:
template:
spec:
containers:
- name: recovery
image: mongo:6.0
command:
- /bin/sh
- -c
- |
mongorestore --host=mongodb-0.mongodb \
--username=$MONGO_ROOT_USERNAME \
--password=$MONGO_ROOT_PASSWORD \
--dir=/backup/latest
env:
- name: MONGO_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_USERNAME
- name: MONGO_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_PASSWORD
volumeMounts:
- name: backup
mountPath: /backup
volumes:
- name: backup
persistentVolumeClaim:
claimName: mongodb-backup
restartPolicy: OnFailure
- 网络策略(network-policy.yaml)
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: mongodb-network-policy
namespace: mongodb
spec:
podSelector:
matchLabels:
app: mongodb
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
access: mongodb
ports:
- protocol: TCP
port: 27017
egress:
- to:
- podSelector:
matchLabels:
app: mongodb
ports:
- protocol: TCP
port: 27017
- 资源配额(resource-quota.yaml)
apiVersion: v1
kind: ResourceQuota
metadata:
name: mongodb-quota
namespace: mongodb
spec:
hard:
requests.cpu: "4"
requests.memory: 8Gi
limits.cpu: "8"
limits.memory: 16Gi
persistentvolumeclaims: "5"
- 监控告警规则(prometheus-rules.yaml)
apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
name: mongodb-alerts
namespace: mongodb
spec:
groups:
- name: mongodb
rules:
- alert: MongoDBHighConnections
expr: mongodb_connections > 1000
for: 5m
labels:
severity: warning
annotations:
summary: High number of connections
- alert: MongoDBReplicaSetLag
expr: mongodb_replset_member_optime_date - on(set) group_right mongodb_replset_member_optime_date{state="PRIMARY"} > 10
for: 5m
labels:
severity: critical
- 集群扩缩容脚本(scale.sh)
#!/bin/bash
# 扩容或缩容MongoDB集群
scale_mongodb() {
local replicas=$1
# 验证输入
if [[ ! $replicas =~ ^[0-9]+$ ]]; then
echo "Please provide a valid number of replicas"
exit 1
}
# 更新StatefulSet
kubectl scale statefulset mongodb -n mongodb --replicas=$replicas
# 等待Pod就绪
kubectl wait --for=condition=ready pod -l app=mongodb -n mongodb --timeout=300s
# 更新复制集配置
update_replica_set_config $replicas
}
# 更新复制集配置
update_replica_set_config() {
local members=""
for ((i=0; i<$1; i++)); do
if [ $i -gt 0 ]; then
members="$members,"
fi
members="$members{_id:$i,host:\"mongodb-$i.mongodb:27017\"}"
done
kubectl exec mongodb-0 -n mongodb -- mongo --eval "
rs.reconfig({
_id: 'rs0',
members: [$members]
})
"
}
- 性能测试Job(benchmark-job.yaml)
apiVersion: batch/v1
kind: Job
metadata:
name: mongodb-benchmark
namespace: mongodb
spec:
template:
spec:
containers:
- name: benchmark
image: mongo:6.0
command:
- /bin/sh
- -c
- |
mongosh --host mongodb-0.mongodb \
--username=$MONGO_ROOT_USERNAME \
--password=$MONGO_ROOT_PASSWORD \
--eval "
for(i=0; i<10000; i++){
db.test.insert({
count: i,
timestamp: new Date()
})
}
"
env:
- name: MONGO_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_USERNAME
- name: MONGO_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_PASSWORD
restartPolicy: Never
- 日志收集配置(fluentd-config.yaml)
apiVersion: v1
kind: ConfigMap
metadata:
name: fluentd-config
namespace: mongodb
data:
fluent.conf: |
<source>
@type tail
path /var/log/mongodb/mongod.log
pos_file /var/log/mongodb/mongod.log.pos
tag mongodb
<parse>
@type regexp
expression /^(?<time>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3})\+\d{4}\s+(?<severity>\w)\s+(?<component>[\w-]+)\s+\[(?<context>[^\]]+)\]\s+(?<message>.*)$/
</parse>
</source>
<match mongodb.**>
@type elasticsearch
host elasticsearch-client
port 9200
logstash_format true
logstash_prefix mongodb
include_tag_key true
</match>
- 维护脚本集合
#!/bin/bash
# 检查MongoDB状态
check_status() {
kubectl exec mongodb-0 -n mongodb -- mongo --eval "rs.status()"
}
# 备份数据
backup() {
kubectl create job --from=cronjob/mongodb-backup mongodb-backup-manual -n mongodb
}
# 恢复数据
restore() {
kubectl apply -f recovery-job.yaml
}
# 清理日志
cleanup_logs() {
kubectl exec -it mongodb-0 -n mongodb -- bash -c "find /var/log/mongodb -name '*.log' -mtime +7 -delete"
}
# 重启服务
restart() {
kubectl rollout restart statefulset mongodb -n mongodb
}
backup)
backup
;;
restore)
restore
;;
cleanup)
cleanup_logs
;;
restart)
restart
;;
*)
echo "Usage: $0 {status|backup|restore|cleanup|restart}"
exit 1
esac
}
main "$@"
- 升级策略(upgrade-strategy.yaml)
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb
namespace: mongodb
spec:
updateStrategy:
type: RollingUpdate
rollingUpdate:
partition: 0 # 控制升级顺序
template:
spec:
containers:
- name: mongodb
image: mongo:6.0 # 版本升级时修改
lifecycle:
preStop:
exec:
command: ["/bin/sh", "-c", "mongosh admin --eval 'db.shutdownServer()'"]
- 灾难恢复流程(disaster-recovery.sh)
#!/bin/bash
# 灾难恢复脚本
DR_BACKUP="/backup/dr"
DR_NAMESPACE="mongodb-dr"
# 创建DR环境
create_dr_env() {
# 创建新命名空间
kubectl create namespace $DR_NAMESPACE
# 复制配置到新命名空间
kubectl get configmap -n mongodb -o yaml | \
sed "s/namespace: mongodb/namespace: $DR_NAMESPACE/" | \
kubectl apply -f -
# 复制密钥
kubectl get secret -n mongodb -o yaml | \
sed "s/namespace: mongodb/namespace: $DR_NAMESPACE/" | \
kubectl apply -f -
}
# 恢复数据
restore_data() {
# 创建恢复Job
cat <<EOF | kubectl apply -f -
apiVersion: batch/v1
kind: Job
metadata:
name: mongodb-dr-restore
namespace: $DR_NAMESPACE
spec:
template:
spec:
containers:
- name: restore
image: mongo:6.0
command:
- mongorestore
- --host=mongodb-0.mongodb.$DR_NAMESPACE
- --username=\$(MONGO_ROOT_USERNAME)
- --password=\$(MONGO_ROOT_PASSWORD)
- --dir=$DR_BACKUP
env:
- name: MONGO_ROOT_USERNAME
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_USERNAME
- name: MONGO_ROOT_PASSWORD
valueFrom:
secretKeyRef:
name: mongodb-secret
key: MONGO_ROOT_PASSWORD
volumeMounts:
- name: backup
mountPath: /backup
volumes:
- name: backup
persistentVolumeClaim:
claimName: mongodb-backup
restartPolicy: OnFailure
EOF
}
- 性能监控Dashboard(grafana-dashboard.json)
{
"dashboard": {
"title": "MongoDB Cluster Dashboard",
"panels": [
{
"title": "Connections",
"type": "graph",
"datasource": "Prometheus",
"targets": [
{
"expr": "mongodb_connections{state=\"current\"}"
}
]
},
{
"title": "Operations",
"type": "graph",
"targets": [
{
"expr": "rate(mongodb_op_counters_total[5m])"
}
]
},
{
"title": "Replica Set Status",
"type": "table",
"targets": [
{
"expr": "mongodb_replset_member_state"
}
]
}
]
}
}
- 自动化测试脚本(test-mongodb.sh)
#!/bin/bash
# 测试MongoDB集群功能
test_mongodb() {
# 测试连接
test_connection() {
kubectl exec mongodb-0 -n mongodb -- \
mongo --eval "db.adminCommand('ping')"
}
# 测试写入
test_write() {
kubectl exec mongodb-0 -n mongodb -- \
mongo --eval "db.test.insert({test: 'data', time: new Date()})"
}
# 测试复制
test_replication() {
kubectl exec mongodb-1 -n mongodb -- \
mongo --eval "db.test.find().sort({_id:-1}).limit(1)"
}
# 执行测试
echo "Testing connection..."
test_connection
echo "Testing write operations..."
test_write
echo "Testing replication..."
test_replication
}
- 集群维护清单
维护任务:
日常检查:
- 检查Pod状态
- 监控资源使用
- 查看复制集状态
- 检查备份状态
周期性任务:
- 更新安全补丁
- 清理旧日志
- 优化索引
- 验证备份
故障处理:
- Pod重启失败
- 复制集同步问题
- 存储空间不足
- 性能下降
使用建议:
-
部署前准备
- 确保存储类配置正确
- 规划资源需求
- 配置网络策略
- 准备监控方案
-
运维注意事项
- 定期检查监控指标
- 做好备份验证
- 及时处理告警
- 保持文档更新
-
安全建议
- 及时更新版本
- 限制网络访问
- 加密敏感数据
- 审计重要操作
-
扩展建议
- 根据负载调整资源
- 合理使用自动扩缩容
- 优化存储配置
- 调整备份策略