安全加固与生产环境检查清单
学习者将逐项检查生产就绪清单,涵盖身份验证、RBAC、TLS、加密、监控和备份策略。
安全加固与生产环境检查清单 是 CoddyKit 上的免费 MongoDB Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 MongoDB Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 MongoDB Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
The Production Readiness Mindset
Production readiness is not a feature — it is a checklist of disciplines applied before the first real user hits your system. A deployment that passes all functional tests but skips security hardening, monitoring, and backup verification is not production-ready. This final lesson walks through the critical production checklist for a MongoDB deployment, covering authentication, RBAC, TLS, encryption, monitoring, backup, and disaster recovery.
Checklist 1: Authentication Enabled
Verify that authentication is enabled and that no unauthenticated connections are possible. On self-hosted MongoDB, confirm security.authorization: enabled in mongod.conf. On Atlas, authentication is mandatory and cannot be disabled. Test by attempting to connect without credentials — the connection must be refused. Confirm that no user has the root or __system role in production application accounts.
// Verify authentication is required
// (attempt to connect without credentials — should fail)
try {
const client = new MongoClient('mongodb://localhost:27017')
await client.connect()
await client.db('admin').command({ ping: 1 })
console.log('AUTH MISSING — unauthenticated connections accepted!')
} catch (e) {
console.log('Good: unauthenticated connections rejected')
}
// List all admin users and their roles
use admin
db.getUsers() // verify no app user has 'root' roleChecklist 2: Least-Privilege RBAC
Audit every database user. Each application service should have only the roles it needs on only the databases it needs to access. Run db.getUsers() for each database and check that no service account holds dbAdminAnyDatabase, readWriteAnyDatabase, or root. Create a user access matrix documenting which service connects with which user, which roles it holds, and why. This matrix is your single source of truth for access reviews.
// Audit access matrix
const accessMatrix = [
{ service: 'api-server', user: 'apiSvc', roles: [{ role: 'readWrite', db: 'ecommerce' }] },
{ service: 'analytics-job', user: 'analyticsSvc', roles: [{ role: 'read', db: 'ecommerce' }] },
{ service: 'backup-agent', user: 'backupAgent', roles: [{ role: 'backup', db: 'admin' }] },
{ service: 'monitoring-exp', user: 'prometheusExp', roles: [{ role: 'clusterMonitor', db: 'admin' }] }
]
// Verify each user's actual roles match the matrix
accessMatrix.forEach(entry => {
const user = db.getSiblingDB('admin').getUser(entry.user)
console.log(entry.service, user ? 'OK' : 'MISSING')
})Checklist 3: TLS Enforced
Confirm that net.tls.mode: requireTLS is active and that all client connections are encrypted. Check the MongoDB log for TLS handshake failures that indicate clients still attempting plaintext connections. On Atlas, TLS is enabled by default and cannot be disabled. For self-hosted deployments, run db.adminCommand({ sslInfo: 1 }) (or check db.serverStatus().network) to verify TLS is active. Reject any deployment where TLS is in allowTLS mode in production.
// Verify TLS is active on the server
const netStatus = db.adminCommand({ serverStatus: 1 }).network
console.log('TLS connections:', netStatus.serviceExecutorTaskStats)
// Confirm connection string includes TLS
// mongodb+srv:// always uses TLS
// Self-hosted: mongodb://host:27017/?tls=true
// Check mongod.conf programmatically
// grep 'mode: requireTLS' /etc/mongod.confChecklist 4: Network Isolation
MongoDB should not be directly accessible from the public internet. On Atlas, verify that the IP Access List does not contain 0.0.0.0/0 (allow all). Use VPC Peering or Private Link to route traffic privately. For self-hosted deployments, bind MongoDB to the private network interface only (net.bindIp: 127.0.0.1,10.0.0.5) and configure firewall rules to allow only application server IPs on port 27017.
# mongod.conf — bind only to localhost and private network interface
net:
bindIp: 127.0.0.1,10.0.0.5 # never 0.0.0.0 in production
port: 27017
# Firewall rule (iptables example — block public access to 27017)
# iptables -A INPUT -p tcp --dport 27017 -s 10.0.0.0/8 -j ACCEPT
# iptables -A INPUT -p tcp --dport 27017 -j DROPChecklist 5: Backup and Point-in-Time Recovery
Production deployments must have a verified, tested backup strategy. On Atlas, enable Continuous Cloud Backup which provides point-in-time recovery to any second within the retention window. For self-hosted, configure daily mongodump snapshots to S3 and test restoration monthly. The key word is tested — a backup that has never been restored is a backup you cannot trust. Run a quarterly disaster recovery drill.
# mongodump — daily backup to S3
mongodump \
--uri 'mongodb://backupAgent:pass@host:27017/?authSource=admin' \
--gzip \
--archive=/tmp/backup-$(date +%Y%m%d).gz
# Upload to S3
aws s3 cp /tmp/backup-$(date +%Y%m%d).gz s3://my-mongo-backups/
# Verify backup integrity — test restore to a separate cluster
mongorestore \
--uri 'mongodb://host2:27017' \
--gzip \
--archive=/tmp/backup-$(date +%Y%m%d).gz \
--dropChecklist 6: Monitoring and Alerting
A production MongoDB deployment needs monitoring on: hardware (CPU, disk I/O, network); MongoDB-specific (connections, opcounters, cache hit ratio, replication lag, lock percentages); and application-level (query latency P99, error rates). Atlas has built-in monitoring and alerting. Self-hosted deployments should integrate with Prometheus (mongodb_exporter) + Grafana or an equivalent. Set alerts before thresholds are exceeded, not after.
// Key Atlas alerts to configure (examples)
const alerts = [
{ metric: 'DISK_UTILIZATION', threshold: '80%', severity: 'WARNING' },
{ metric: 'CPU_SYSTEM_NORMALIZED', threshold: '70%', severity: 'WARNING' },
{ metric: 'REPLICATION_LAG', threshold: '10s', severity: 'CRITICAL' },
{ metric: 'CONNECTIONS', threshold: '80%', severity: 'WARNING' },
{ metric: 'CACHE_DIRTY_BYTES', threshold: '20%', severity: 'WARNING' }
]Checklist 7: Query Performance Baseline
Before launch, establish a query performance baseline: enable the profiler at level 1, run representative load (using a tool like MongoDB's load generator or k6), and capture the P95 and P99 latencies for each critical endpoint. Store these baselines. After each deployment, re-run the load test and compare. Any P99 regression above 20% triggers investigation before the deployment reaches all users.
// Enable profiler and set slow query threshold
db.setProfilingLevel(1, { slowms: 50 }) // log queries > 50ms
// After load test, query profiler for summary
db.system.profile.aggregate([
{
$group: {
_id: '$ns',
avgMs: { $avg: '$millis' },
maxMs: { $max: '$millis' },
count: { $sum: 1 },
slowOps: { $sum: { $cond: [{ $gt: ['$millis', 100] }, 1, 0] } }
}
},
{ $sort: { avgMs: -1 } }
])Checklist 8: Encryption at Rest
For applications handling PII, payment data, or health information, verify that encryption at rest is enabled. On Atlas, enable cloud provider KMS-based encryption in the Security settings. For self-hosted Enterprise deployments, confirm security.enableEncryption: true and a KMIP key manager is configured. Document which Customer Master Key protects which cluster and ensure the CMK itself has multi-person access controls to prevent lockout.
// Verify Atlas encryption at rest is enabled via Atlas Admin API
curl -u 'PUBLIC_KEY:PRIVATE_KEY' --digest \
'https://cloud.mongodb.com/api/atlas/v1.0/groups/GROUP_ID/encryptionAtRest'
// Response should show: 'awsKms.enabled': true (or azure/gcp equivalent)
// For self-hosted, check mongod.conf
// grep 'enableEncryption' /etc/mongod.conf
// Expected: enableEncryption: trueChecklist 9: Audit Logging
Enable audit logging to record every authentication, authorisation failure, and sensitive data access event. MongoDB Enterprise and Atlas provide audit log streams that you can route to a SIEM (Security Information and Event Management) system. Configure audit filters to capture: all authenticate actions, all createUser/dropUser/updateUser actions, and all operations on sensitive collections (users, payments). Retain audit logs for at least 1 year for compliance.
# mongod.conf — enable audit logging (Enterprise)
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.json
filter: '{
atype: {
$in: ["authenticate", "authCheck", "createUser", "dropUser",
"logout", "createCollection", "dropCollection"]
}
}'Checklist 10: Runbook and Disaster Recovery Plan
Document operational procedures in a runbook: how to connect to MongoDB in an emergency, how to restart a failed replica set member, how to perform a manual failover, how to restore from backup, and what the escalation path is. Practice these procedures in a staging environment. Set a Recovery Time Objective (RTO) — how long can the database be down — and a Recovery Point Objective (RPO) — how much data loss is acceptable. Atlas's continuous backup provides an RPO of seconds.
// Runbook checklist (document in your team wiki)
const runbook = {
emergencyConnect: 'mongosh mongodb+srv://adminUser:***@cluster.mongodb.net',
checkReplicaStatus: 'rs.status()',
triggerManualFailover: 'rs.stepDown() // on current primary',
viewReplicationLag: 'rs.printSlaveReplicationInfo()',
restoreFromBackup: 'atlas backups restores start --clusterName prod',
contactList: ['dba-oncall@company.com', '+1-800-DBA-HELP'],
rto: '15 minutes',
rpo: '5 seconds (continuous backup)'
}Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this capstone's final lesson you completed the production readiness checklist: authentication, least-privilege RBAC, TLS, network isolation, backup + tested restore, monitoring, query performance baseline, encryption at rest, audit logging, and a written runbook. Congratulations — you have now completed the full MongoDB & NoSQL Databases track, from first document insert to sharded cluster production deployment. Take these skills and build something great!
用 AI 导师学习 JavaScript — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「安全加固与生产环境检查清单」课时是免费的吗?
是的 — 「安全加固与生产环境检查清单」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 MongoDB Academy 课程的其余内容,请升级到 CoddyKit PRO。 MongoDB Academy 课程共包含 4 节课。
「安全加固与生产环境检查清单」这节课中我会学到什么?
学习者将逐项检查生产就绪清单,涵盖身份验证、RBAC、TLS、加密、监控和备份策略。 你通过在浏览器中直接运行的动手代码来练习 MongoDB Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 MongoDB Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 MongoDB Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「安全加固与生产环境检查清单」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 MongoDB Academy 课中编写并运行代码吗?
能。每节 MongoDB Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 需求分析与模式设计
- 索引策略与查询规划器验证
- 扩展计划:从副本集到分片集群
- 安全加固与生产环境检查清单