Docker & Containers

Running MongoDB in a Docker Container on CentOS, AlmaLinux, and RockyLinux

By the Domain India teamPublished 7 min read
Knowledge base article
Contents (9 sections)

Running MongoDB in a Docker container keeps the database separate from the rest of your server, makes the version easy to pin and upgrade, and lets you rebuild it with one command. This guide installs Docker Engine on AlmaLinux or Rocky Linux, runs the official MongoDB image with persistent storage and authentication, and covers backups and upgrades. It applies to your own VPS or server with root access, not to shared hosting.

Key takeaways

Install Docker Engine from Docker's own repository, then run the official mongo image with a pinned version tag, a named volume for /data/db, a root user set through environment variables, and the port published only on 127.0.0.1. Without a volume your data disappears with the container, and without the 127.0.0.1 binding Docker can expose port 27017 to the internet even when your firewall looks closed. Back up with mongodump from inside the container.

This guide is for your own server

Docker needs root access, so it runs on a VPS or dedicated server, not on shared hosting. For why, see Docker on cPanel and DirectAdmin: the honest truth. CentOS Linux 7 and 8 are end of life; use AlmaLinux or Rocky Linux 9 (or 8) instead. The commands for both are the same.

1. Before you start

You need:

  • A server running AlmaLinux or Rocky Linux 9 or 8, with root or sudo access.
  • At least 2 GB of RAM for a small database. MongoDB uses about half of the available memory for its cache by default.
  • A CPU with AVX support. MongoDB 5.0 and later need it on x86_64 servers, and a container does not change that. Check first:
bash
grep -qw avx /proc/cpuinfo && echo "AVX OK" || echo "No AVX: MongoDB 5+ will not start"

If AVX is missing, read Downgrading MongoDB to version 4.4 before you go further.

2. Install Docker Engine

Update the system and remove older container packages that conflict with Docker (on a fresh server most of these are not installed, and that's fine):

bash
sudo dnf -y upgrade
sudo dnf -y remove podman buildah runc

Add Docker's repository and install Docker Engine with the Compose plugin:

bash
sudo dnf -y install dnf-plugins-core
sudo dnf config-manager --add-repo https://download.docker.com/linux/rhel/docker-ce.repo
sudo dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
sudo systemctl enable --now docker
sudo docker run --rm hello-world

The last command pulls a tiny test image and prints a welcome message if Docker works. The old docker-compose command is replaced by docker compose (with a space), which the plugin provides.

3. Run MongoDB with storage and a password

Choose a version and pin it. mongo:latest changes under you when a new major version appears, which can break an upgrade. At the time of writing MongoDB 8.0 is the current major release; check Docker Hub for newer ones.

bash
sudo docker volume create mongo-data

sudo docker run -d --name mongodb \
  --restart unless-stopped \
  -p 127.0.0.1:27017:27017 \
  -v mongo-data:/data/db \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD='use-a-long-random-password' \
  mongo:8.0

What each part does:

OptionWhy it matters
--restart unless-stoppedStarts MongoDB again after a reboot or crash
-p 127.0.0.1:27017:27017Makes MongoDB reachable only from the server itself
-v mongo-data:/data/dbKeeps the data in a named volume that survives the container
MONGO_INITDB_ROOT_USERNAME and _PASSWORDCreates an admin user and turns on authentication on first start
mongo:8.0Pins the major version so updates stay within 8.0

The root user is created only when the data volume is empty. Changing the environment variables later does not change an existing password.

Docker can bypass your firewall

When you publish a port as -p 27017:27017, Docker writes its own firewall rules, and the port can be open to the internet even if firewalld says it is closed. Open MongoDB servers are found by scanners within hours and their data is wiped for ransom. Always publish on 127.0.0.1, as above, and reach the database from your computer through an SSH tunnel: ssh -N -L 27017:127.0.0.1:27017 user@your-server-ip.

4. Check that it works

bash
sudo docker ps
sudo docker logs --tail 50 mongodb
sudo docker exec -it mongodb mongosh -u admin -p --authenticationDatabase admin

At the mongosh prompt, db.runCommand({ ping: 1 }) should return { ok: 1 }. The old mongo shell is no longer included in current images; use mongosh.

5. Create an app user

Don't let your application log in as the root user. Inside mongosh:

javascript
use appdb
db.createUser({ user: "appuser", pwd: passwordPrompt(), roles: [{ role: "readWrite", db: "appdb" }] })

An app on the same server connects with:

text
mongodb://appuser:[email protected]:27017/appdb?authSource=appdb

If the app also runs in Docker, put both containers on the same Docker network and use the container name (mongodb:27017) as the host instead of 127.0.0.1.

6. The same setup with Docker Compose

A Compose file keeps the whole configuration in one place and out of your shell history. Save this as compose.yaml, with the password in a .env file next to it (chmod 600 .env):

yaml
services:
  mongodb:
    image: mongo:8.0
    container_name: mongodb
    restart: unless-stopped
    ports:
      - "127.0.0.1:27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: ${MONGO_ROOT_PASSWORD}
    volumes:
      - mongo-data:/data/db

volumes:
  mongo-data:
bash
echo "MONGO_ROOT_PASSWORD=use-a-long-random-password" > .env
chmod 600 .env
sudo docker compose up -d

7. Back up and restore

A volume is not a backup. Dump the data to a compressed archive on the host:

bash
sudo docker exec mongodb sh -c \
  'mongodump -u admin -p "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --archive --gzip' \
  > mongo-$(date +%F).archive.gz

Restore with mongorestore the same way, feeding the archive in:

bash
sudo docker exec -i mongodb sh -c \
  'mongorestore -u admin -p "$MONGO_INITDB_ROOT_PASSWORD" --authenticationDatabase admin --archive --gzip' \
  < mongo-2026-09-23.archive.gz

Run the backup from cron, keep several days of archives, and copy them off the server. Test a restore on a spare container now and then.

8. Upgrade or change versions

Minor updates within a version are simple:

bash
sudo docker pull mongo:8.0
sudo docker stop mongodb && sudo docker rm mongodb
# run the same docker run command as before (or: sudo docker compose up -d)

The data stays in the volume. Major upgrades (for example 7.0 to 8.0) must go one major version at a time, with featureCompatibilityVersion set at each step, and a backup first; follow MongoDB's upgrade notes.

Going backwards is different. Pointing an older image such as mongo:4.4 at a volume written by a newer version fails, because the data files are not compatible. Start the older version with a new, empty volume and restore from a mongodump archive. MongoDB 4.4 has been end of life since February 2024, so use it only as a stopgap on a CPU without AVX.

9. Running this on Domain India

A Domain India VPS gives you KVM virtualisation, full root access and a choice of Linux distribution, so Docker and everything in this guide run as written. The VPS is self-managed: you look after updates, security and backups. If you prefer MongoDB installed directly on the server rather than in a container, follow installing MongoDB on a Domain India VPS.

MongoDB is not available from shared hosting, and our shared servers' outbound firewall does not allow MongoDB's usual port, so an outside service such as MongoDB Atlas can't normally be reached from there either. Use a VPS, the App Platform (test the connection from your app), or MySQL or PostgreSQL instead. Choosing between PostgreSQL, MySQL, SQLite and MongoDB compares them.

VPS Starter
₹552.65/mo + GST
  • 1 vCPU
  • 2 GB DDR4 RAM
  • 64 GB NVMe SSD Storage
  • 2 TB Monthly Bandwidth
See plan details
VPS Basic
₹1,105.30/mo + GST
  • 2 vCPU
  • 4 GB DDR4 RAM
  • 128 GB NVMe SSD Storage
  • 3 TB Monthly Bandwidth
See plan details

Prices on the cards are live Domain India list prices and exclude 18% GST.

Is it safe to run MongoDB in Docker in production?

Yes, if you store data in a volume, pin the image version, enable authentication, publish the port only on 127.0.0.1 and take regular mongodump backups that you copy off the server. Most problems come from missing one of those.

Why did my MongoDB data disappear when I removed the container?

The container was started without a volume, so the data lived inside the container and was deleted with it. Always mount a named volume or a host directory at /data/db.

Why is my MongoDB port open to the internet when firewalld blocks it?

Docker adds its own firewall rules for published ports, which take effect before firewalld's zone rules. Publish the port as 127.0.0.1:27017:27017 and connect remotely through an SSH tunnel.

Why does the MongoDB container exit with "Illegal instruction"?

MongoDB 5.0 and later need a CPU with AVX support on x86_64. Check with grep avx /proc/cpuinfo. A container cannot add AVX; use a server that has it, or see our MongoDB 4.4 guide for the risks of the stopgap.

Which command replaced the mongo shell?

mongosh. Run it inside the container with docker exec -it mongodb mongosh.

Can I run MongoDB on Domain India shared hosting?

No. Shared hosting cannot run Docker or a MongoDB server, and outbound connections to MongoDB's usual port are blocked. Use a Domain India VPS or the App Platform instead.

Ready to run MongoDB? Compare VPS plans, or read the native MongoDB install guide if you'd rather not use Docker.

Get a VPS for Docker and MongoDB

KVM VPS with full root access and your choice of Linux distribution.

See VPS plans

Was this article helpful?

Your answer helps us decide what to improve next.

Still need help? Open a support ticket and our team will reply.

Prefer an app? Add this site to your home screen.Get the app
MongoDB in Docker on AlmaLinux & Rocky Linux | Domain India