0Pricing
MongoDB Academy · Aula

Reforço da segurança e lista de verificação de produção

Os alunos percorrerão uma lista de verificação de prontidão para produção que abrange autenticação, RBAC, TLS, criptografia, monitoramento e estratégia de backup.

Reforço da segurança e lista de verificação de produção é uma aula grátis de MongoDB Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de MongoDB Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de MongoDB Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em 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' role

Checklist 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.conf

Checklist 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 DROP

Checklist 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 \
  --drop

Checklist 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: true

Checklist 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!

Perguntas Frequentes

A aula “Reforço da segurança e lista de verificação de produção” é grátis?

Sim — o texto completo de “Reforço da segurança e lista de verificação de produção” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de MongoDB Academy, atualize para CoddyKit PRO. O curso de MongoDB Academy inclui 4 aulas no total.

O que vou aprender em “Reforço da segurança e lista de verificação de produção”?

Os alunos percorrerão uma lista de verificação de prontidão para produção que abrange autenticação, RBAC, TLS, criptografia, monitoramento e estratégia de backup. Você pratica MongoDB Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar MongoDB Academy?

Nenhuma experiência prévia é necessária. MongoDB Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Reforço da segurança e lista de verificação de produção”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de MongoDB Academy?

Sim. Cada aula de MongoDB Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Análise de requisitos e projeto de esquema
  2. Estratégia de índices e validação do planejador de consultas
  3. Plano de escalabilidade: de conjunto de réplicas a cluster fragmentado
  4. Reforço da segurança e lista de verificação de produção
← Voltar para MongoDB Academy