VPS Tutorials
MongoDB 8 on a VPS: TLS, replica bootstrap and tested backups
Deploy MongoDB 8.0.38 with a single-member replica set and private TLS. Correct client-certificate settings, mount permissions, authenticated account creation and CA paths, then verify oplog backups and isolated recovery.

MongoDB deployment problems usually arise from exposure, missing authentication, an uninitialized replica set, certificate mismatches, memory pressure or backups that have never been restored—not from inserting the first JSON document.
This Ubuntu 24.04 and Docker Compose guide runs MongoDB Community as a single-member replica set, with SCRAM accounts, an internal keyfile, mandatory TLS, private ports, bounded resources and oplog-aware backups. The original September 11, 2026 patch was 8.0.32. The official image and release notes checked on November 16 provide 8.0.38-noble, released November 10. Use that reviewed 8.0 patch for a fresh installation; avoid latest and review security notices before upgrades. The earlier comparison with the 8.3 stable series is historical, not a claim that it remains the latest series.
- Changing product attributes, content metadata or user configuration.
- Nested documents usually read or written together.
- Event, device, catalog and content-management applications.
- Projects needing change streams, document transactions or future scale planning.
Choose from query patterns, transaction boundaries and data lifecycle. Relational constraints, financial consistency and joins may suit PostgreSQL/MySQL better; relevance-oriented full-text search often suits Elasticsearch. JSON-shaped data alone is not sufficient justification.
Initializing one mongod as a replica set provides:
- An oplog for change streams.
- Multi-document transaction support.
mongodump --oplogto capture writes during a full logical backup.
It provides no host-failure tolerance and only one online data copy.
| Architecture | Redundancy | Automatic failover | Use |
|---|---|---|---|
| Standalone | None | None | Temporary testing |
| One-member replica set | None | None | Recoverable small deployments needing transactions/change streams |
| Three independent data-bearing nodes | Yes | With an available voting majority | Critical workloads and rolling maintenance |
| Three members on one VPS | Shared host failure | Entire deployment fails with the host | Learning only |
Evaluate latency, elections, majority write concern and inter-region traffic before distributing nodes. Replication propagates erroneous updates/deletions; independent backups remain necessary.
WiredTiger uses its own cache plus filesystem cache.
| Workload | Suggested VPS | Cache starting point | Assumption |
|---|---|---|---|
| Development | 2 vCPU, 4GB RAM, 40GB SSD | 1GB | Light, rebuildable data |
| Small production | 4 vCPU, 8GB RAM, 100GB NVMe | 1.5–2GB | Room for cache, Docker and monitoring |
| Critical service | At least 3 hosts, 4–8 vCPU and 16GB+ each | Load-tested | Separate failure domains and off-host backups |
The example limits the container to 4GB and WiredTiger cache to 1.5GB. Connections, aggregation, indexing and compression need additional memory; setting cache near the limit risks killing mongod.
Prefer NVMe and monitor data, indexes, journal and oplog growth. XFS is strongly recommended for WiredTiger; EXT4 is supported but should be tested with the actual write workload. MongoDB 8.0 production guidance recommends enabling Transparent Huge Pages, unlike advice for 7.0 and earlier.
| Port | Purpose | Exposure |
|---|---|---|
27017/TCP | Clients | 127.0.0.1 only |
Internal 27017 | Application/database traffic | Compose network |
22/TCP | Administration/tunneling | Restricted sources and SSH keys |
Do not publish 27017:27017 universally. Use Docker private networking, VPN/cloud private routes or SSH tunnels with TLS validation. Check the database exposure guide.
Install Docker Engine and Compose v2 using the official Ubuntu instructions first:
sudo apt update
sudo apt full-upgrade -y
sudo apt install -y ca-certificates curl jq openssl
docker --version
docker compose version
uname -r
On amd64, ensure the virtual CPU exposes AVX and the image supports your architecture. Official release notes warn about TCMalloc incompatibility from kernel 6.19 through 7.0.13; 7.0.14 or newer resolves that interval. Check uname -r rather than assuming every Ubuntu 24.04 host still uses its original kernel.
Use the Compose production checklist for health, logs and resource limits.
sudo install -d -m 0750 -o "$USER" -g "$USER" \
/opt/mongodb/{config,secrets,tls,backups}
cd /opt/mongodb
umask 077
MONGO_ADMIN_PASSWORD="$(openssl rand -hex 32)"
MONGO_APP_PASSWORD="$(openssl rand -hex 32)"
MONGO_BACKUP_PASSWORD="$(openssl rand -hex 32)"
{
printf 'MONGODB_VERSION=8.0.32-noble\n'
printf 'MONGO_ADMIN_USER=mongoAdmin\n'
printf 'MONGO_ADMIN_PASSWORD=%s\n' "$MONGO_ADMIN_PASSWORD"
printf 'MONGO_APP_USER=appUser\n'
printf 'MONGO_APP_PASSWORD=%s\n' "$MONGO_APP_PASSWORD"
printf 'MONGO_BACKUP_USER=backupUser\n'
printf 'MONGO_BACKUP_PASSWORD=%s\n' "$MONGO_BACKUP_PASSWORD"
} > .env
chmod 600 .env
This creates new secrets and overwrites the environment file; do not run it against established credentials. Keep .env private and avoid publishing expanded docker compose config. Hex passwords simplify URI escaping; a secret manager is preferable.
Select the checked patch before startup:
cd /opt/mongodb
sed -i 's/^MONGODB_VERSION=.*/MONGODB_VERSION=8.0.38-noble/' .env
chmod 600 .env
cd /opt/mongodb
openssl rand -base64 756 > secrets/mongodb-keyfile
chmod 400 secrets/mongodb-keyfile
sudo chown 999:999 secrets/mongodb-keyfile
MongoDB accepts 6–1024 base64 key characters and requires restrictive Unix permissions. Future members must securely share at least one common key. Never distribute it through public repositories or ordinary chat.
Cover mongo, localhost and 127.0.0.1. Before signing, set the server.ext extendedKeyUsage line to serverAuth,clientAuth: a replica-set daemon can act as both TLS server and internal client.
cd /opt/mongodb/tls
openssl genrsa -out ca.key 4096
openssl req -x509 -new -sha256 -days 3650 \
-key ca.key \
-subj '/CN=VPS MongoDB Internal CA' \
-out ca.crt
openssl genrsa -out server.key 4096
openssl req -new -sha256 \
-key server.key \
-subj '/CN=mongo' \
-out server.csr
{
printf 'subjectAltName=DNS:mongo,DNS:localhost,IP:127.0.0.1\n'
printf 'extendedKeyUsage=serverAuth\n'
printf 'keyUsage=digitalSignature,keyEncipherment\n'
} > server.ext
openssl x509 -req -sha256 -days 825 \
-in server.csr \
-CA ca.crt -CAkey ca.key -CAcreateserial \
-extfile server.ext \
-out server.crt
cat server.crt server.key > server.pem
chmod 600 ca.key server.key server.pem
chmod 644 ca.crt server.crt
sudo chown 999:999 server.pem
openssl verify -CAfile ca.crt server.crt
openssl x509 -in server.crt -noout -subject -issuer -dates -ext subjectAltName
server.pem contains the certificate and matching private key. For multiple hosts, issue appropriate node DNS SANs through managed internal PKI. Certificates used for internal TLS client connections may need clientAuth as well as serverAuth; plan that before expanding. Never rely on tlsAllowInvalidCertificates or tlsAllowInvalidHostnames to bypass trust.
Create /opt/mongodb/config/mongod.conf:
storage:
dbPath: /data/db
wiredTiger:
engineConfig:
cacheSizeGB: 1.5
net:
port: 27017
bindIpAll: true
tls:
mode: requireTLS
certificateKeyFile: /etc/mongo/tls/server.pem
CAFile: /etc/mongo/tls/ca.crt
replication:
replSetName: rs0
security:
authorization: enabled
keyFile: /etc/mongo/secrets/mongodb-keyfile
setParameter:
diagnosticDataCollectionEnabled: true
For the SCRAM-over-TLS clients in this guide, add the following property inside the existing net.tls section, alongside mode, CAFile and certificateKeyFile:
allowConnectionsWithoutCertificates: true
Its default is false, which would require client certificates that these commands do not supply. True still requires encrypted connections and authenticated accounts after bootstrap; presented client certificates are still validated. For a deliberate mTLS deployment, retain false and provision compatible client certificates instead.
bindIpAll concerns container-side listening. Exposure still depends on 127.0.0.1:27017:27017, Docker routing and firewalls. Do not replace it with 0.0.0.0.
Create /opt/mongodb/compose.yml:
services:
mongo:
image: mongo:${MONGODB_VERSION}
container_name: mongodb
restart: unless-stopped
command: ["mongod", "--config", "/etc/mongo/mongod.conf"]
ports:
- "127.0.0.1:27017:27017"
environment:
MONGO_ADMIN_USER: ${MONGO_ADMIN_USER}
MONGO_ADMIN_PASSWORD: ${MONGO_ADMIN_PASSWORD}
MONGO_APP_USER: ${MONGO_APP_USER}
MONGO_APP_PASSWORD: ${MONGO_APP_PASSWORD}
MONGO_BACKUP_USER: ${MONGO_BACKUP_USER}
MONGO_BACKUP_PASSWORD: ${MONGO_BACKUP_PASSWORD}
volumes:
- mongo-data:/data/db
- ./config/mongod.conf:/etc/mongo/mongod.conf:ro
- ./secrets:/etc/mongo/secrets:ro
- ./tls:/etc/mongo/tls:ro
- ./backups:/backups
mem_limit: 4g
ulimits:
nofile:
soft: 64000
hard: 64000
healthcheck:
test:
- CMD-SHELL
- >-
mongosh --quiet --host localhost --port 27017 --tls
--tlsCAFile /etc/mongo/tls/ca.crt
-u "$${MONGO_ADMIN_USER}" -p "$${MONGO_ADMIN_PASSWORD}"
--authenticationDatabase admin
--eval 'quit(db.adminCommand({ping:1}).ok ? 0 : 2)'
interval: 15s
timeout: 10s
retries: 20
start_period: 90s
logging:
driver: json-file
options:
max-size: 10m
max-file: "5"
networks:
- mongo-net
volumes:
mongo-data:
networks:
mongo-net:
name: mongo-net
The original 8.0.32-noble tag is a pinned historical example; the environment change selects the reviewed current patch. These custom account variables do not trigger image user creation—the explicit bootstrap below does.
Before starting, set ownership for the selected image. Chowning just the keyfile is insufficient when its parent directory is inaccessible, and the database container must be able to write backups:
cd /opt/mongodb
MONGO_SELECTED_IMAGE="$(docker compose config --images)"
MONGO_CONTAINER_UID="$(docker run --rm --entrypoint id "$MONGO_SELECTED_IMAGE" -u mongodb)"
MONGO_CONTAINER_GID="$(docker run --rm --entrypoint id "$MONGO_SELECTED_IMAGE" -g mongodb)"
sudo chown "$MONGO_CONTAINER_UID:$MONGO_CONTAINER_GID" secrets tls backups
sudo chmod 750 secrets tls
sudo chmod 700 backups
sudo chown "$MONGO_CONTAINER_UID:$MONGO_CONTAINER_GID" secrets/mongodb-keyfile tls/server.pem
sudo chmod 400 secrets/mongodb-keyfile
sudo chmod 600 tls/server.pem
sudo chown "root:$MONGO_CONTAINER_GID" config/mongod.conf
sudo chmod 640 config/mongod.conf
unset MONGO_SELECTED_IMAGE MONGO_CONTAINER_UID MONGO_CONTAINER_GID
This assumes one service in the Compose project. Keep the CA signing key owned separately with mode 600 and exclude it from application access; privileged maintenance may be needed after changing directory ownership.
cd /opt/mongodb
docker compose config --quiet
docker compose pull
docker compose up -d
docker compose logs --tail=100 mongo
Until an administrator exists, authenticated health checks may report starting or unhealthy. Use the localhost exception only for the initial replica-set bootstrap:
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
--eval '
rs.initiate({
_id: "rs0",
members: [{ _id: 0, host: "mongo:27017" }]
})
'
until docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
--eval 'quit(db.hello().isWritablePrimary ? 0 : 2)'
do
sleep 2
done
members[0].host is mongo:27017, resolvable on mongo-net. Remote replica-aware clients need routable member names and matching SANs; tunneling a bootstrap port alone does not make the advertised container name reachable. For single-host tunnel diagnostics, directConnection=true can select that one member; use proper private topology for ongoing remote replica-set access.
The localhost exception ends after the first user is created. In the following script, insert this line immediately after the administrator createUser call and before creating the application or backup account:
admin.auth(process.env.MONGO_ADMIN_USER, process.env.MONGO_ADMIN_PASSWORD);
Then use the bootstrap:
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
--eval '
const admin = db.getSiblingDB("admin");
admin.createUser({
user: process.env.MONGO_ADMIN_USER,
pwd: process.env.MONGO_ADMIN_PASSWORD,
roles: [{ role: "root", db: "admin" }]
});
const app = db.getSiblingDB("appdb");
app.createUser({
user: process.env.MONGO_APP_USER,
pwd: process.env.MONGO_APP_PASSWORD,
roles: [{ role: "readWrite", db: "appdb" }]
});
admin.createUser({
user: process.env.MONGO_BACKUP_USER,
pwd: process.env.MONGO_BACKUP_PASSWORD,
roles: [
{ role: "backup", db: "admin" },
{ role: "restore", db: "admin" }
]
});
'
docker compose ps
If the script previously stopped after creating the administrator, authenticate as that administrator and create only the missing users; do not delete storage or rerun initialization. Use appUser in applications, never mongoAdmin. The example combines backup/restore roles for simplicity; production backup accounts should keep backup only, with recovery credentials separate.
cd /opt/mongodb
set -a
. ./.env
set +a
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_ADMIN_USER" -p "$MONGO_ADMIN_PASSWORD" \
--authenticationDatabase admin \
--eval '
printjson(db.hello());
printjson(rs.status().members.map(m => ({name:m.name,stateStr:m.stateStr})));
'
Expect setName: "rs0", isWritablePrimary: true and PRIMARY. Check permitted application access to appdb:
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_APP_USER" -p "$MONGO_APP_PASSWORD" \
--authenticationDatabase appdb \
--eval '
const app = db.getSiblingDB("appdb");
app.healthcheck.insertOne({checkedAt:new Date(),source:"deploy"});
printjson(app.healthcheck.findOne({source:"deploy"}));
'
Also verify the application cannot perform administrative operations or access unrelated databases. Use the URI pattern:
mongodb://appUser:PASSWORD@mongo:27017/appdb?authSource=appdb&replicaSet=rs0&tls=true&tlsCAFile=/run/secrets/mongodb-ca.crt
Replace PASSWORD securely, keep real URIs out of Git and percent-encode any reserved characters.
services:
app:
image: your-app:stable
networks:
- app-net
- mongo-net
secrets:
- mongodb_ca
networks:
app-net:
mongo-net:
external: true
secrets:
mongodb_ca:
file: ./secrets/mongodb-ca.crt
The sample app image is a placeholder. Copy only /opt/mongodb/tls/ca.crt into the application's restricted secret path. Compose's default secret filename is mongodb_ca, while the URI uses mongodb-ca.crt: set the secret's target to mongodb-ca.crt or update the URI path to /run/secrets/mongodb_ca. Applications never need the server key, member keyfile or administrator password.
--oplog records writes during a full dump; --oplogReplay replays them:
cd /opt/mongodb
docker compose exec -T mongo sh -lc '
set -eu
ts="$(date -u +%Y%m%dT%H%M%SZ)"
mongodump \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_BACKUP_USER" -p "$MONGO_BACKUP_PASSWORD" \
--authenticationDatabase admin \
--oplog --gzip \
--archive="/backups/mongodb-${ts}.archive.gz"
sha256sum "/backups/mongodb-${ts}.archive.gz" \
> "/backups/mongodb-${ts}.archive.gz.sha256"
'
find backups -maxdepth 1 -type f -printf '%TY-%Tm-%Td %TH:%TM %s %f\n' | sort
This is a whole-instance backup, not a filtered single-database procedure. Ensure the oplog window exceeds backup duration and avoid unsupported concurrent topology/collection changes. Check the command succeeded and the archive is readable.
/opt/mongodb/backups shares the host failure domain. Encrypt and upload archives/digests to independent object storage with separate credentials, server-side encryption, lifecycle/retention rules and versioning. The checksum uses a container-absolute path; adjust the verification path when checking a downloaded archive outside that container.
For large datasets, mongodump can impose significant CPU/I/O/network cost. Evaluate supported consistent storage snapshots, Ops Manager/Cloud Manager or Atlas and backup impact on the primary.
Never try --drop on production. Prepare a separate compatible replica set, copy the archive/CA and create restoreUser with the tool's required permissions:
mongorestore \
--host localhost --port 27017 \
--tls --tlsCAFile /path/to/ca.crt \
-u restoreUser -p \
--authenticationDatabase admin \
--drop --gzip \
--archive=/path/to/mongodb-20260916T120000Z.archive.gz \
--oplogReplay
Oplog replay needs privileges beyond the ordinary restore role. Give the isolated restore account the documented additional privilege of anyAction on anyResource, then remove that broad recovery privilege after the exercise. The full dump can restore users/roles too, so retain the backed-up administrator credentials rather than assuming the temporary account will survive.
Verify databases/collections, sample records, indexes, accounts, application reads/writes and replication state. mongodump is not a host image: separately encrypt and back up .env, CA/private keys, mongod configuration, monitoring and recovery instructions. Preserve historical archive dates as examples and substitute the actual saved filename.
opcounters, latency and slow queries.- Connection use, available capacity and creation rate.
- WiredTiger cache, dirty bytes, eviction and checkpoints.
- Page faults, memory, swap and OOM events.
- Data, index, journal/oplog sizes and I/O latency.
- Replica health, lag, elections and majority-write failures.
- Backup duration, size, upload and restore results.
Use Prometheus and Grafana. serverStatus and dbStats provide basic signals:
db.serverStatus().connections
db.serverStatus().wiredTiger.cache
db.serverStatus().opcounters
db.getSiblingDB("appdb").stats(1024 * 1024)
rs.printReplicationInfo()
Fix queries/indexes and bound result sets before increasing cache or hardware. More indexes consume memory/disk and increase write cost. Validate real queries with explain("executionStats").
Read release notes, complete an off-host backup and test recovery:
cd /opt/mongodb
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_ADMIN_USER" -p "$MONGO_ADMIN_PASSWORD" \
--authenticationDatabase admin \
--eval 'printjson(db.adminCommand({getParameter:1,featureCompatibilityVersion:1}))'
docker compose pull mongo
docker compose up -d mongo
docker compose ps
docker compose logs --tail=150 mongo
Change the explicit patch first; pulling the same tag alone does not change versions. Check version, replica state, application access, slow queries and backups afterward. Avoid mongo:8 as an uncontrolled series transition. Follow supported major-version steps and postpone FCV changes until all members/drivers are compatible; raising FCV can restrict rollback.
A single node has downtime. Independent replica sets require the supported secondary/primary rolling sequence, not simultaneous recreation.
cd /opt/mongodb
docker compose ps
docker compose logs --since=15m --tail=300 mongo
docker inspect mongodb --format '{{.State.Status}} {{.State.ExitCode}} {{.State.OOMKilled}}'
Inspect keyfile/server.pem and parent permissions, YAML, data-volume access, memory and kernel compatibility using the container restart guide.
ls -l /opt/mongodb/secrets/mongodb-keyfile
sudo chown 999:999 /opt/mongodb/secrets/mongodb-keyfile
sudo chmod 400 /opt/mongodb/secrets/mongodb-keyfile
docker compose restart mongo
Check the actual image UID/GID and parent directory too. Never use chmod 777; MongoDB rejects group/world-readable keys.
openssl verify -CAfile /opt/mongodb/tls/ca.crt \
/opt/mongodb/tls/server.crt
openssl x509 -in /opt/mongodb/tls/server.crt \
-noout -ext subjectAltName
For mongo, include DNS:mongo; for 127.0.0.1, include its IP SAN. Check CA trust and expiry rather than bypassing verification.
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_ADMIN_USER" -p "$MONGO_ADMIN_PASSWORD" \
--authenticationDatabase admin \
--eval 'printjson(rs.status())'
On one member, verify mongo:27017, the original network and data volume. For multiple members check DNS, clocks, keyfile, SANs, routes and voting majority.
ss -lntp | grep 27017
docker network inspect mongo-net
docker compose exec -T mongo mongosh --quiet \
--host localhost --port 27017 \
--tls --tlsCAFile /etc/mongo/tls/ca.crt \
-u "$MONGO_ADMIN_USER" -p "$MONGO_ADMIN_PASSWORD" \
--authenticationDatabase admin \
--eval 'db.adminCommand({ping:1})'
Verify the app joined mongo-net. Before considering 0.0.0.0, establish VPN/private/tunnel access and matching DNS/SANs. See port/firewall diagnostics.
Inspect docker inspect, dmesg, cache and concurrent aggregation. Reducing cacheSizeGB alone will not fix unbounded $group, large sorts/results or index builds. Bound queries and leave resource headroom.
Development can start around 2 vCPU/4GB; small production commonly needs 4 vCPU/8GB and NVMe. Measure working set, queries, cache and disk latency.
No. It enables oplog, transactions and change streams. Host-failure tolerance needs independent voting/data-bearing members, monitoring and backups.
Keep 127.0.0.1 for host access, Docker networking locally and private/VPN/tunnel routes remotely, preserving TLS and authorization.
Floating tags may introduce compatibility changes. The historical 8.0.32-noble and the reviewed replacement are explicit patches; update deliberately after testing recovery.
No. It suits manageable logical datasets; also preserve keys/configuration and off-host archives. Evaluate snapshots or supported managed tooling for large/critical systems.
Replication provides redundancy/failover. Sharding distributes capacity/work across shards, each typically a replica set. Avoid the extra complexity before measured capacity limits require it.