Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
VGSources
Blog

How to Run MongoDB in a Docker Container on a VPS

A practical guide to running MongoDB 8 in Docker on a VPS, including Compose configuration, persistent storage, secure connectivity, backups, upgrades, and recovery.
Length11 min Posted Quest giverVGSources Team
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable pattern is a Docker Compose project with the official mongo:8 image, a named volume mounted at /data/db, initialized authentication credentials, and no publicly exposed database port unless you have a specific remote-access requirement. Applications on the same Compose network connect to mongodb:27017; a host process uses a port bound to 127.0.0.1 and, when needed, an SSH tunnel.

This guide builds that deployment, verifies it, explains the connection strings, and covers the security, backup, upgrade, and recovery work that makes a VPS installation dependable rather than merely reachable.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What the deployment looks like

Docker runs the MongoDB server inside one container. Docker Compose supplies the project lifecycle, a private network shared by the project’s services, and a named volume for database files. The volume is mounted at MongoDB’s standard data directory, /data/db, so recreating the container does not remove the database files.

  • MongoDB service: the official mongo:8 image listens on port 27017 inside the container.
  • Authentication: MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD create the initial root account when the database is initialized.
  • Storage: the named volume mongo-data is managed by Docker and mounted at /data/db.
  • Networking: other containers on the same Compose network use the service name mongodb; they do not use the VPS’s loopback address.
  • Host access: publishing 127.0.0.1:27017:27017 makes MongoDB available to programs on the VPS without opening the port to the internet.

A named volume is persistence, not a backup. If the VPS, its disk, or the Docker volume is lost, only a separate, tested backup can restore the data.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.

Prerequisites and decisions

There is no universal CPU, memory, or disk size for MongoDB. Your document count, indexes, working set, write rate, and backup retention determine the VPS capacity. The deployment itself needs the following:

Requirement What to confirm
Linux VPS You have administrator access, a supported Linux distribution, enough disk for data, indexes, logs, and backup staging, and a firewall or cloud security group you can control.
Docker Engine Docker is installed and the account running Compose can access the Docker socket.
Docker Compose The modern Compose plugin is available, so docker compose (with a space) works.
Storage plan Database storage and backup storage are separate capacity decisions. A volume on the same VPS does not protect against VPS loss.
Application location Decide whether the application will be another container in this Compose project, a process on the VPS, or a remote client. That choice determines the connection address.
Remote administration If you need to inspect the database from your workstation, plan an SSH tunnel instead of opening port 27017 publicly.

A fixed RAM or disk recommendation would be misleading without a workload. Monitor actual disk consumption, memory pressure, and query behavior after deployment, then resize the VPS deliberately.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Create the Compose project

1. Make a dedicated directory

  1. Connect to the VPS over SSH.
  2. Create and enter a directory owned by the account that will run Compose:
mkdir -p ~/mongodb-vps
cd ~/mongodb-vps

Keeping the Compose file and its environment file together makes lifecycle commands predictable. Restrict access to the directory because it will contain credentials or references to them.

2. Choose how credentials are supplied

The official image requires an initial root username and password when an empty data directory is initialized. The sample values below are intentionally obvious; replace them before starting the service. Do not commit a real password to a public repository.

Create a file named .env in the project directory:

MONGO_INITDB_ROOT_USERNAME=change-me
MONGO_INITDB_ROOT_PASSWORD=use-a-long-secret

Set restrictive permissions:

chmod 600 .env

Compose reads this file for variable substitution. Keep it out of source control and out of screenshots, tickets, and shell history. For a larger operation, use your host’s secret-management process; whichever mechanism you choose must still provide the two variables to the image during initialization.

3. Write compose.yaml

Save this file as compose.yaml:

services:
  mongodb:
    image: mongo:8
    restart: unless-stopped
    environment:
      MONGO_INITDB_ROOT_USERNAME: ${MONGO_INITDB_ROOT_USERNAME}
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_INITDB_ROOT_PASSWORD}
    volumes:
      - mongo-data:/data/db
    # Publish only when a host process must connect.
    # ports:
    #   - '127.0.0.1:27017:27017'

volumes:
  mongo-data:

The service is deliberately not published to a host port in the baseline. That leaves it reachable through the private Compose network while preventing unsolicited internet connections. Uncomment the two ports lines only when a process outside the Compose network genuinely needs host access, and keep the address bound to 127.0.0.1.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed

Before starting anything, ask Compose to render and validate the configuration:

docker compose config

Check that the image, environment values, volume, and any port mapping are what you intended. This command can display substituted secrets, so avoid sharing its output.

Start MongoDB and verify the first initialization

  1. Start the service in the background:
docker compose up -d
  1. Check the service state:
docker compose ps

The MongoDB service should show as running. A container that repeatedly exits needs its logs examined before you continue.

  1. Read the startup and initialization log:
docker compose logs --tail=100 mongodb

You can also inspect a specific container with docker logs <container-name> after obtaining its name from docker compose ps. Look for errors about configuration, permissions, disk space, or an already-initialized data directory.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Confirm that Docker created the declared volume:
docker volume ls
docker volume inspect mongodb-vps_mongo-data

The exact volume name is project-scoped. If you run the project from a different directory or with a different Compose project name, the prefix can differ; use docker volume ls to identify the actual name.

  1. Run a database-shell check from inside the container. This works even when no host port is published:
docker compose exec mongodb mongosh 'mongodb://change-me:[email protected]:27017/admin'

Replace both sample credentials with the values used for this initialized database. A successful shell connection verifies the server, authentication, and local container path. The root account is created in the admin authentication database, which is why the connection string includes /admin.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Connect an application correctly

Application in the same Compose project

Containers on a Compose network resolve one another by service name. Configure the application with a URI like:

mongodb://change-me:use-a-long-secret@mongodb:27017/appdb?authSource=admin

Here, mongodb is the Compose service name, not a hostname you must add to DNS. The application should not use 127.0.0.1: inside the application container, that address points back to the application container itself.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If the application is added to the same compose.yaml, it automatically joins the default project network unless you explicitly change the network configuration. Start both services with the same docker compose up -d command and verify each service separately with docker compose ps.

Application running directly on the VPS

Uncomment this mapping in compose.yaml:

ports:
  - '127.0.0.1:27017:27017'

Recreate the service so the mapping takes effect:

docker compose up -d

The host application can then use:

mongodb://change-me:[email protected]:27017/appdb?authSource=admin

Binding to loopback means the port is not listening on the VPS’s public interfaces. Confirm the listener and your firewall policy rather than assuming a port is private.

Administrator connecting from a workstation

Do not expose MongoDB directly to the internet for convenience. With the loopback mapping enabled, create an SSH tunnel from your workstation:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
ssh -L 27017:127.0.0.1:27017 user@your-vps-host

Keep that SSH session open and point a local MongoDB shell or client at 127.0.0.1:27017. The traffic travels through SSH, while MongoDB remains bound to the VPS loopback interface. Close the tunnel when finished.

Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Secure a public VPS

Initialize authentication before exposure

An internet-exposed MongoDB instance must not run without a root username and password. Initialize credentials through the image variables and replace the sample values before deployment. If the volume already contains a database, changing the environment file does not retroactively change existing users; perform account changes through MongoDB’s administrative commands and verify them before removing any old credential.

Keep port 27017 off the public interface

  • Prefer no ports entry when only Compose services need MongoDB.
  • Use 127.0.0.1:27017:27017 for a host-side application or SSH-tunnel administration.
  • If a remote application truly requires direct access, restrict the source IPs in the VPS firewall and cloud security group, require authentication, and understand that a published port is now part of your internet attack surface.

Apply least privilege at the VPS layer

Allow only the SSH, application, and monitoring traffic you actually need. Keep the operating system, Docker Engine, Compose plugin, and MongoDB image maintained. A Docker network isolates ordinary service traffic, but it is not a substitute for host patching, firewall rules, or database authentication.

Protect configuration and secrets

Do not place real credentials in a committed compose.yaml. Protect .env, limit who can read the project directory, and review command history when passwords were typed directly into commands. Compose supports isolated networks and secret-handling patterns, but declaring a secret does not by itself initialize the MongoDB account; wire the chosen secret source into the image’s required variables and test the result.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Persistence, backup, and restore

What the named volume protects

The declaration mongo-data:/data/db stores MongoDB files outside the container’s writable layer. Running docker compose down and recreating the service leaves that named volume in place unless you explicitly remove it. This is why a container restart or image replacement does not normally erase the database.

Never use docker compose down -v casually: the -v option removes project volumes and can destroy the only copy of the data. Inspect volumes before deleting anything:

docker volume ls
docker volume inspect mongodb-vps_mongo-data

Make a MongoDB-aware backup

A volume is not an off-host backup. Schedule a MongoDB-aware logical backup, copy it to storage independent of the VPS, and periodically perform a test restore. One simple archive backup, run from the project directory, is:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
mkdir -p backups
docker compose exec -T mongodb mongodump 
  --username change-me 
  --password 'use-a-long-secret' 
  --authenticationDatabase admin 
  --archive > backups/mongo-$(date +%F).archive

The archive is written on the VPS by shell redirection. Protect it as carefully as the live database because it contains database contents. Avoid putting a production password in a shared script; use your protected secret mechanism when automating.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Test a restore procedure

A backup is only useful if it can be read. Restore into a disposable MongoDB environment first, or into a planned maintenance window after confirming the target. For an archive piped into the running service:

cat backups/mongo-2026-10-15.archive | docker compose exec -T mongodb mongorestore 
  --username change-me 
  --password 'use-a-long-secret' 
  --authenticationDatabase admin 
  --archive

Do not add destructive options such as --drop until you have verified the target database and understand exactly which collections will be replaced. Choose a backup naming and retention policy that matches how much data loss your application can tolerate; the deployment itself does not provide that policy.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Update the image without gambling the data

  1. Confirm that a recent backup exists off the VPS and that a restore has been tested.
  2. Review MongoDB release compatibility and the image tag you intend to use. Treat a major-version change as a migration decision, not an ordinary restart.
  3. Record the current image tag and application connection settings so you can diagnose a change.
  4. Pull the selected image:
docker compose pull mongodb
  1. Recreate the service:
docker compose up -d mongodb
  1. Immediately inspect status and logs, then run the mongosh check and an application connectivity test:
docker compose ps
docker compose logs --tail=100 mongodb
docker compose exec mongodb mongosh 'mongodb://change-me:[email protected]:27017/admin'

Do not delete the named volume as part of an upgrade. If the new image is incompatible, stop and follow the supported MongoDB migration or rollback procedure for that release; downgrading a database’s files blindly can make recovery harder.

Troubleshooting by symptom

Symptom Likely cause Checks and corrective action
The container exits immediately Invalid configuration, insufficient disk, permission failure, or an image startup error. Run docker compose logs mongodb. Check free disk space, confirm the environment variables are present with docker compose config, and inspect the volume mount.
Authentication fails after editing .env The volume was already initialized with different credentials. Remember that initialization variables create the first account; they do not reset an existing database. Use the currently valid administrative account to change credentials, or follow a documented recovery procedure.
The application says connection refused It is using the wrong address, the service is not running, or no host port is published. From another container use mongodb:27017. From a VPS host process use 127.0.0.1:27017 only after enabling the loopback mapping. Check docker compose ps and logs.
A remote client cannot connect MongoDB is correctly bound to loopback, or firewall rules block the port. Use the SSH tunnel method. If direct remote access is unavoidable, verify the published interface, source-IP firewall rule, and security-group rule without opening the port to everyone.
The port cannot be published Another process already owns host port 27017. Inspect the existing listener, stop or reconfigure the conflicting service, or choose a different host port while keeping the container port at 27017. Update the host connection string accordingly.
Data seems to disappear after recreation The service was started from a different Compose project, a different volume was mounted, or the volume was removed. Run docker volume ls and docker volume inspect, compare the project directory and volume name, and check that the mount target is exactly /data/db. Do not run down -v while investigating.
MongoDB starts but the application still fails The server is ready at a different time than the application, or the URI has incorrect credentials or authentication database. Test with mongosh, verify the URI uses authSource=admin for the initialized root account, and have the application retry connection during startup rather than assuming container start order means database readiness.

Self-managed container or managed MongoDB?

A Dockerized database on a VPS gives you control over image tags, maintenance windows, network placement, and storage. It also makes you responsible for the host, disk, firewall, upgrades, monitoring, backup scheduling, and restore tests. A managed database shifts much of that operational work to the provider. The right choice depends on who will perform those tasks, not just on whether a container can be started.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Decision area Self-managed Docker deployment Managed database
Operational responsibility You administer Docker, Linux, MongoDB, networking, monitoring, and recovery. The provider handles the service platform; you still configure users, access, and application integration.
Backups and restore You schedule MongoDB-aware backups, copy them off-host, and test restores. Backup and restore tooling depends on the provider’s plan and retention policy; verify those details before relying on them.
Network exposure You control private Compose networking, loopback bindings, firewalls, and tunnels. You use the provider’s network controls, allowlists, and endpoints.
Scaling and replica sets You must design and operate scaling, replication, and any replica-set requirements. The provider may offer built-in scaling and replication, subject to its product limits.
Upgrade control You choose image tags and maintenance timing, while handling compatibility. The provider controls more of the platform lifecycle, with whatever version options it exposes.
Monthly cost No single amount can be stated: VPS size, storage, backup destination, and traffic determine it. No comparable amount is established here; pricing varies by provider, region, capacity, and features.

Deployment checklist

  • Docker Engine and the Compose plugin run successfully on the Linux VPS.
  • The project directory is protected, and real credentials replace the sample values.
  • compose.yaml uses mongo:8, initializes authentication, and mounts mongo-data at /data/db.
  • MongoDB is not publicly published unless a documented requirement justifies it.
  • Same-network applications use mongodb:27017; host applications use a loopback mapping; remote administration uses SSH.
  • docker compose ps, logs, mongosh, and volume inspection all produce the expected results.
  • Backups are MongoDB-aware, stored away from the VPS, and restored in a test procedure.
  • Image changes are preceded by a tested backup and followed by log, shell, and application checks.

This arrangement keeps MongoDB private by default, retains its files across container recreation, and leaves the operational responsibilities visible: protect the credentials, control the network, maintain the image and host, and prove that recovery works.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.