Refuerzo de la seguridad y lista de comprobación para producción
Revise una lista de comprobación de preparación para producción que abarque autenticación, RBAC, TLS, cifrado, supervisión y estrategia de copias de seguridad.
Refuerzo de la seguridad y lista de comprobación para producción es una lección gratuita de MongoDB Academy en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de MongoDB Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de MongoDB Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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!
Preguntas frecuentes
¿La lección «Refuerzo de la seguridad y lista de comprobación para producción» es gratis?
Sí — el texto completo de «Refuerzo de la seguridad y lista de comprobación para producción» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de MongoDB Academy, actualiza a CoddyKit PRO. El curso de MongoDB Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Refuerzo de la seguridad y lista de comprobación para producción»?
Revise una lista de comprobación de preparación para producción que abarque autenticación, RBAC, TLS, cifrado, supervisión y estrategia de copias de seguridad. Practicas MongoDB Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar MongoDB Academy?
No se requiere experiencia previa. MongoDB Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Refuerzo de la seguridad y lista de comprobación para producción»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de MongoDB Academy?
Sí. Cada lección de MongoDB Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Análisis de requisitos y diseño de esquemas
- Estrategia de índices y validación del planificador de consultas
- Plan de escalado: de replica set a clúster fragmentado
- Refuerzo de la seguridad y lista de comprobación para producción