Skip to content

MongoDB Production Setup ​

Production Checklist ​

Hardware & Configuration:

yaml
# mongod.conf (production)
storage:
  dbPath: /data/mongo
  # journal luôn bật; mongod 8 từ chối storage.journal.enabled ("Unrecognized option: storage.journal.enabled")
  engine: wiredTiger  # Default, recommended
  wiredTiger:
    engineConfig:
      cacheSizeGB: 48  # ví dụ cho máy 96 GB RAM; bỏ dòng này để dùng mặc định của WiredTiger
    collectionConfig:
      blockCompressor: snappy  # Balance: speed + compression

systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true
  logRotate: reopen  # Use with logrotate

net:
  port: 27017
  # Chỉ IP riêng. RISK: ĐỪNG đặt 0.0.0.0 khi chưa bật authorization và firewall
  bindIp: 10.0.1.5,127.0.0.1
  maxIncomingConnections: 5000

security:
  authorization: enabled  # ALWAYS enable!
  # Thành viên replica set xác thực nhau bằng keyFile (tạo: openssl rand -base64 756 > /etc/mongo/keyfile; chmod 400)
  keyFile: /etc/mongo/keyfile
  # Muốn dùng x509 (clusterAuthMode: x509) thì phải bật net.tls (mode + certificateKeyFile + CAFile):
  # thiếu TLS thì mongod thoát với "need to enable TLS via the tlsMode flag"

replication:
  replSetName: rs0  # Replica set name
  oplogSizeMB: 51200  # ví dụ 50 GB; chọn theo cửa sổ oplog cần, đo bằng rs.printReplicationInfo()

setParameter:
  # Chỉ đặt false SAU khi đã tạo user admin đầu tiên (bật rồi thì createUser báo "requires authentication")
  enableLocalhostAuthBypass: false  # Security
  cursorTimeoutMillis: 600000  # 10 minutes

Connection pooling:

javascript
// Node.js (minh hoạ, không chạy độc lập: host primary/secondary1/secondary2 là placeholder, thay bằng host thật)
const { MongoClient } = require('mongodb')

const client = new MongoClient('mongodb://primary:27017,secondary1:27017,secondary2:27017/mydb', {
  replicaSet: 'rs0',

  // Connection pool (critical for performance)
  maxPoolSize: 100,  // Max connections per server
  minPoolSize: 10,   // Min connections to maintain

  // Timeouts
  connectTimeoutMS: 10000,  // 10s to establish connection
  socketTimeoutMS: 45000,   // 45s for socket operations
  serverSelectionTimeoutMS: 30000,  // 30s to select server

  // Write concern (production)
  w: 'majority',  // Wait for majority of nodes
  journal: true,  // Wait for journal commit
  wtimeoutMS: 5000,  // 5s timeout for write concern

  // Read preference
  readPreference: 'primaryPreferred',  // Primary if available

  // Retry
  retryWrites: true,  // Automatic retry on transient errors
  retryReads: true
})

Monitoring Queries ​

1. Check replication lag:

javascript
// mongosh (chạy được trên mọi thành viên; đã chạy trên replica set 3 nút mongo:8)
rs.status()

// Look for:
// - members[].optime.ts (oplog timestamp)
// - members[].optimeDate (human-readable lag)

// Ngưỡng lag tuỳ SLA ứng dụng (ví dụ minh hoạ: cảnh báo khi > 10 giây)
db.printReplicationInfo()  // Shows oplog range
rs.printSecondaryReplicationInfo()  // Shows lag for each secondary

2. Check slow queries:

javascript
// mongosh (đã chạy trên mongo:8; chạy trong database cần theo dõi)
// Enable profiling (level 1 = slow queries only)
db.setProfilingLevel(1, { slowms: 100 })  // Log queries > 100ms

// View slow queries:
db.system.profile.find().sort({ ts: -1 }).limit(10).pretty()

// Find most common slow operations:
db.system.profile.aggregate([
  { $match: { millis: { $gt: 100 } } },
  { $group: {
    _id: { ns: "$ns", op: "$op" },
    count: { $sum: 1 },
    avgMs: { $avg: "$millis" },
    maxMs: { $max: "$millis" }
  }},
  { $sort: { count: -1 } },
  { $limit: 10 }
])

3. Check index usage:

javascript
// mongosh (minh hoạ: thay `collection` bằng tên collection thật; $indexStats đã chạy OK trên mongo:8)
// Find unused indexes (run after 7+ days):
db.collection.aggregate([
  { $indexStats: {} },
  { $match: { "accesses.ops": { $lt: 100 } } },  // <100 uses since mongod start or index creation (counters reset on restart)
  { $project: { name: 1, "accesses.ops": 1 } }
])

// Check index sizes:
db.collection.stats().indexSizes

// Find missing indexes (check explain plans):
db.currentOp({
  "secs_running": { $gte: 5 },  // Running 5+ seconds
  "op": "query",
  "planSummary": /COLLSCAN/  // Collection scan (no index)
})

4. Check connection pool:

javascript
// mongosh
db.serverStatus().connections
/*
Kết quả minh hoạ (đo trên mongo:8 với maxIncomingConnections: 5000, đã rút gọn):
{
  current: 17,
  available: 4983,   // số kết nối còn mở được thêm, KHÔNG phải tổng
  totalCreated: 45   // nếu tăng nhanh bất thường → kiểm tra connection leak
}
*/

// Cảnh báo khi current / (current + available) > 0.8

5. Check working set vs cache:

javascript
// mongosh
db.serverStatus().wiredTiger.cache
/*
Kết quả minh hoạ (rút gọn):
{
  "bytes currently in the cache": 48318382080,
  "maximum bytes configured": 51539607552,
  "tracked bytes belonging to internal pages in the cache": 1283471,
  "tracked bytes belonging to leaf pages in the cache": 48317098609,
  "bytes read into cache": 2834718923776,
  "bytes written from cache": 1283471283
}
*/

// "bytes read into cache" là bộ đếm tích luỹ từ lúc mongod khởi động: lấy hiệu hai lần đo
// cách nhau vài phút để ra tốc độ đọc từ đĩa vào cache (không phải kích thước working set).
// Tốc độ đọc cao liên tục và "bytes currently in the cache" sát "maximum bytes configured"
// → working set lớn hơn cache: tăng RAM/cacheSizeGB hoặc shard

Backup Strategies ​

1. Replica set backup (khuyên dùng):

javascript
// mongosh: tạo hidden secondary để backup (không nhận read traffic)
cfg = rs.conf()
cfg.members[2].priority = 0  // hidden bắt buộc priority 0, không thể thành primary
cfg.members[2].hidden = true  // ẩn với ứng dụng
cfg.members[2].votes = 0  // tuỳ chọn: đổi số phiếu làm đổi đa số bầu cử của replica set
rs.reconfig(cfg)

Backup từ hidden secondary (đã chạy trên replica set 3 nút mongo:8 có keyFile + auth: dump rồi restore vào instance sạch ra đủ 500 document). --oplog cho bản chụp nhất quán tại thời điểm dump kết thúc, KHÔNG phải khôi phục về thời điểm tuỳ ý:

bash
# minh hoạ: host và đường dẫn là placeholder; thêm --username/--authenticationDatabase khi bật auth
mongodump \
  --host=hidden-secondary:27017 \
  --gzip \
  --archive=/backup/mongo-$(date +%Y%m%d).gz \
  --oplog

# Restore vào instance sạch:
mongorestore \
  --gzip \
  --archive=/backup/mongo-20250109.gz \
  --oplogReplay

2. Filesystem snapshot (nhanh hơn với dataset lớn): Chạy trên hidden secondary: nếu chạy nhầm fsyncLock() trên primary thì mọi ghi của cả ứng dụng bị chặn. fsyncUnlock() không bắt buộc cùng phiên mongosh với fsyncLock() (đo trên mongo:8: mở khoá từ phiên khác trả lockCount: 0, lần mở thứ hai báo "fsyncUnlock called when not locked"). Thời gian khoá = thời gian chờ lệnh snapshot trả về, đo trên hệ thống của bạn (đổi theo storage). Khoá/mở khoá đã chạy trên mongo:8:

javascript
// mongosh, kết nối tới hidden secondary
db.fsyncLock()
bash
# Snapshot volume (LVM, EBS...). Ví dụ EBS (chưa chạy: dịch vụ quản lý AWS):
aws ec2 create-snapshot \
  --volume-id vol-1234567890abcdef0 \
  --description "MongoDB backup $(date +%Y%m%d)"
javascript
// mongosh (có thể ở phiên khác với db.fsyncLock(), nhưng phải cùng thành viên)
db.fsyncUnlock()

3. Continuous backup (MongoDB Atlas / Ops Manager):

text
Atlas Cloud Backup: chu kỳ snapshot và cửa sổ PITR do Backup Policy của cluster quy định
(chưa chạy: dịch vụ quản lý; xem trang cấu hình Backup của cluster).

Khôi phục thủ công:
1. Atlas UI → Backup tab
2. Chọn snapshot hoặc thời điểm
3. Restore sang cluster mới

Security Hardening ​

1. Bật xác thực (SCRAM-SHA-256):

javascript
// mongosh tương tác (`use` là lệnh của mongosh, không dùng được trong file script)
use admin
db.createUser({
  user: "admin",
  pwd: passwordPrompt(),  // mật khẩu nhập tại prompt
  roles: [ "root" ]
})

// Create app user (least privilege):
use myapp
db.createUser({
  user: "app_user",
  pwd: passwordPrompt(),
  roles: [
    { role: "readWrite", db: "myapp" },
    { role: "read", db: "myapp_analytics" }
  ]
})

Tạo user trước, rồi bật xác thực trong mongod.conf và restart (đã chạy: createUser OK trên cụm 3 nút; khi enableLocalhostAuthBypass: false mà chưa có user thì createUser báo "requires authentication"):

yaml
security:
  authorization: enabled

2. Enable TLS/SSL:

yaml
# mongod.conf:
net:
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongo-server.pem  # minh hoạ: đường dẫn placeholder, thiếu file thì mongod FATAL "Can not set up PEM key file"
    CAFile: /etc/ssl/ca.pem

Chuỗi kết nối phía client (không phải nội dung mongod.conf):

text
mongodb://user:pass@host:27017/db?tls=true&tlsCAFile=/path/to/ca.pem

3. Network security:

bash
# Firewall (iptables):
iptables -A INPUT -p tcp --dport 27017 -s 10.0.1.0/24 -j ACCEPT  # App servers only (ACCEPT đứng trước DROP: luật xét theo thứ tự)
iptables -A INPUT -p tcp --dport 27017 -j DROP  # Block all others

Hoặc giới hạn interface lắng nghe bằng net.bindIp trong mongod.conf (mặc định là localhost). RISK: ĐỪNG đặt 0.0.0.0 khi chưa bật authorization và firewall:

yaml
net:
  bindIp: 10.0.1.5,127.0.0.1  # Only listen on private IPs

4. Audit logging (Enterprise):

yaml
# mongod.conf:
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{ atype: { $in: [ "authenticate", "createUser", "dropDatabase" ] } }'

Phải nhớ (MongoDB production):

  • Bật authorization, net.bindIp chỉ IP riêng và TLS trước khi mở cổng; ĐỪNG đặt bindIp: 0.0.0.0 khi chưa có auth và firewall.
  • Backup trên hidden secondary và thử restore thật (mongorestore --oplogReplay) định kỳ.
  • Theo dõi lag (rs.status()), kết nối (current / (current + available)) và tốc độ đọc vào cache.