0Pricing
MongoDB Academy · Урок

Усиление безопасности и контрольный список для рабочей среды

Учащиеся пройдут контрольный список готовности к рабочей среде, включающий аутентификацию, RBAC, TLS, шифрование, мониторинг и стратегию резервного копирования.

«Усиление безопасности и контрольный список для рабочей среды» — бесплатный урок MongoDB Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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' 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!

Часто задаваемые вопросы

Урок «Усиление безопасности и контрольный список для рабочей среды» бесплатный?

Да — полный текст урока «Усиление безопасности и контрольный список для рабочей среды» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс MongoDB Academy, подпишись на CoddyKit PRO. Курс MongoDB Academy содержит 4 уроков всего.

Чему я научусь в уроке «Усиление безопасности и контрольный список для рабочей среды»?

Учащиеся пройдут контрольный список готовности к рабочей среде, включающий аутентификацию, RBAC, TLS, шифрование, мониторинг и стратегию резервного копирования. Ты практикуешь MongoDB Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать MongoDB Academy?

Предыдущий опыт не требуется. MongoDB Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.

Сколько времени занимает урок «Усиление безопасности и контрольный список для рабочей среды»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке MongoDB Academy?

Да. Каждый урок MongoDB Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Анализ требований и проектирование схемы
  2. Стратегия индексации и проверка планировщика запросов
  3. План масштабирования: от набора реплик до сегментированного кластера
  4. Усиление безопасности и контрольный список для рабочей среды
← Назад к MongoDB Academy