October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk10 min

How to Set Up Rails With MongoDB on an Ubuntu VPS

Install MongoDB from the supported Ubuntu repository, secure it before exposure, connect Rails with Mongoid, and verify the complete application path.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The reliable pattern is to run MongoDB on an Ubuntu LTS VPS, keep mongod on localhost or a private network, enable authentication before any public exposure, and connect Rails through Mongoid. Install MongoDB from the official repository that matches your Ubuntu release, manage it with systemd, create a least-privilege database user, then configure the production Mongoid URI through a secret rather than committing credentials.

A deployment is not complete when the service merely says “active.” You must verify MongoDB itself, authenticate with the application account, and complete a Rails read/write request from the deployed process.

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 finished architecture looks like

For the simplest deployment, Rails and MongoDB run on the same VPS. MongoDB listens on 127.0.0.1:27017, so database traffic never leaves the machine. Rails connects through Mongoid, which reads its environment-specific settings from config/mongoid.yml.

If Rails and MongoDB are on different VPSs, place them on a private network. Bind MongoDB only to its loopback address and private interface, restrict the database port in the firewall to the Rails server’s private address, and require authentication. Do not treat a public IP address as a substitute for network controls.

Choose the VPS and Ubuntu release first

Match Ubuntu to the MongoDB release

Provision an Ubuntu LTS release that is explicitly supported by the MongoDB version you intend to install. The repository package, service files and default paths are tied to that support matrix; choosing an arbitrary Ubuntu image can leave you with unavailable packages or an unsupported combination.

Decide where each service belongs

  • Single VPS: easiest networking and lowest administrative overhead. Use localhost binding and leave port 27017 closed externally.
  • Separate database VPS: useful when application and database resources must be isolated. Use a private interface, a source-restricted firewall rule and encrypted connections where your topology requires them.
  • Managed database: removes much of the operating-system and database-service work, but you trade direct control for the provider’s supported regions, backup model, scaling controls and recurring price. Confirm those details for the service and region you select.

Record the Ubuntu release, MongoDB release, VPS private address, database name and intended Rails environment before installing anything. Those values determine the repository entry and the final Mongoid configuration.

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

Update Ubuntu and install MongoDB

1. Update the operating system

sudo apt-get update
sudo apt-get upgrade -y

Reboot if the update process installs a new kernel or tells you that a reboot is required. Reconnect over SSH before continuing.

2. Add MongoDB’s official Ubuntu repository

Use MongoDB’s current Ubuntu installation documentation to add the signing key and repository stanza for your exact Ubuntu LTS codename and the MongoDB release you selected. Do not copy a repository line for a different Ubuntu release. After the repository is configured, refresh the package index:

sudo apt-get update

3. Install the server packages

sudo apt-get install -y mongodb-org

The official packages install the mongod service, its command-line tools and the standard configuration under /etc/mongod.conf. On Ubuntu, the default database files are under /var/lib/mongodb. Keep that directory owned by the operating-system account used by the service; changing ownership casually can prevent startup.

Start, enable and inspect mongod with systemd

Start the service now

sudo systemctl start mongod
systemctl status mongod

The status output should show active (running). If it is failed, do not repeatedly restart it; read the service log first:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo journalctl -u mongod

Common early failures are a malformed YAML setting, a repository/package mismatch, a port already in use, or incorrect permissions on /var/lib/mongodb.

Make it persistent across reboots

sudo systemctl enable mongod

Enabling a unit affects future boots; it does not replace the initial start command. After a reboot, confirm both that systemd started MongoDB and that Rails can still authenticate.

Run a local server check

mongosh --eval 'db.runCommand({ ping: 1 })'

A successful response proves that a local MongoDB process is listening. It does not prove that authentication, the application account or the Rails connection is correct.

Secure MongoDB before exposing any network interface

MongoDB binaries bind to localhost by default. Keep that safe default whenever Rails is on the same VPS. MongoDB’s hardening guidance requires access control and authentication before binding to a publicly accessible address, along with network restrictions that limit trusted clients.

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

Create an administrator through the local connection

Connect locally while the server is still reachable on localhost:

mongosh

Create an administrative user in the admin database. The localhost exception permits creation of the first user on a new, otherwise unsecured deployment; after that, use authenticated sessions.

use admin
db.createUser({
  user: 'site_admin',
  pwd: passwordPrompt(),
  roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ]
})

passwordPrompt() keeps the password out of the shell command and, in turn, out of ordinary shell history. Store the credential in your password manager or deployment secret store.

Create a separate Rails account with only application privileges

Do not give the web application an all-database administrator role. Create the application database first, then grant the Rails account only the permissions it needs:

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.
use myDB
db.createUser({
  user: 'rails_app',
  pwd: passwordPrompt(),
  roles: [ { role: 'readWrite', db: 'myDB' } ]
})

Use a different database name and username for each application when practical. A dedicated account makes credential rotation and incident response less disruptive.

Enable authorization in the configuration

Edit /etc/mongod.conf and ensure the network and security sections express your intended boundary:

net:
  bindIp: 127.0.0.1
  port: 27017
security:
  authorization: enabled

If the database and Rails are on separate machines, replace the bind address with the loopback address plus the VPS’s private interface address, not a wildcard public bind. Keep the private address protected by the VPS firewall.

Restart and verify with an authenticated connection:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo systemctl restart mongod
mongosh --username rails_app --authenticationDatabase myDB --password --host 127.0.0.1 --eval 'use myDB; db.runCommand({ ping: 1 })'

When the command prompts for a password and returns a successful ping, authorization is active. If the restart fails, inspect sudo journalctl -u mongod and correct the YAML or file permissions before changing anything else.

Close the network boundary

Single-VPS firewall policy

Allow SSH only from the administration sources you trust, and allow HTTP/HTTPS as required by the Rails application. Do not add a public inbound rule for TCP 27017; Rails reaches MongoDB over loopback.

Separate-VPS policy

Allow TCP 27017 only from the Rails server’s private address. Deny all other sources, keep authentication enabled, and avoid publishing the database address in DNS intended for the public internet. If the private network is unavailable, use an encrypted tunnel rather than opening MongoDB broadly.

Why binding alone is not enough

A localhost or private bind reduces exposure but does not replace users, roles, firewall rules, patching or backups. A compromised application server can still reach a database on its private network, so application credentials must remain least-privilege and rotatable.

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

Add Mongoid to Rails

Install the adapter

Add a Mongoid version compatible with your Rails and Ruby versions to the application’s Gemfile:

gem 'mongoid'
bundle install

Mongoid is the layer Rails uses to load the MongoDB client and map document models. You must configure Mongoid before using any Mongoid component.

Generate the baseline configuration

bin/rails g mongoid:config

The generator creates config/mongoid.yml and an initializer. Inspect the generated file instead of replacing it blindly; keep the environment names that match the way you deploy Rails.

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

Configure development or a same-VPS test environment

The simplest configuration points to localhost:27017 and names a database:

development:
  clients:
    default:
      database: myDB_development
      hosts:
        - localhost:27017

Mongoid’s basic configuration follows this pattern: a named environment, a default client, a database and one or more hosts. With authorization enabled, add credentials for the appropriate database rather than relying on an anonymous connection.

Configure production without committing secrets

Use a secret-managed URI

For production, supply a complete MongoDB URI through the VPS environment or your deployment secret manager. Keep the URI out of Git, application logs and error pages. A URI for a local database normally contains the Rails username, password, host, port and database name; URL-encode reserved characters in a password.

production:
  clients:
    default:
      uri: <%= ENV.fetch('MONGODB_URI') %>

If your deployment system does not use a URI, Mongoid also supports separate host, database and authentication settings. Whichever form you choose, keep one source of truth for production credentials and verify that the Rails process actually receives it.

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

Check file permissions and process environment

  • Make the secret readable by the Rails service account, not by every user on the VPS.
  • Never print MONGODB_URI in a startup script, health endpoint or diagnostic page.
  • After rotating a password, update the secret and restart the Rails process so the connection pool is rebuilt.
  • When using a private database host, verify that the Rails VPS can resolve and route to that private address.

Verify the connection from Rails

First, test Mongoid’s client

Run a Rails command as the same Unix user and with the same environment that your application server uses:

bin/rails runner 'puts Mongoid.default_client.database.command(ping: 1).inspect'

This checks that Rails loaded config/mongoid.yml, expanded the secret and established a MongoDB session. A successful MongoDB shell test alone cannot catch a missing production environment variable or a malformed URI.

Then perform an application-level read/write check

Use an existing document model in a controlled environment, or add a temporary health-check model that you remove after validation. For example, with an Order document containing a status field:

bin/rails runner 'record = Order.create!(status: "connection_probe"); puts Order.where(id: record.id).exists?; record.destroy!'

The command should create, query and delete one document. Run it against a non-production database first; if you must test production, use a clearly marked probe and remove it immediately. This verifies permissions such as readWrite, not merely the ability to authenticate.

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

Check the deployed process, not only your shell

SSH sessions often have different environment variables from systemd, a process manager or a container. Run the check through the same release command or service account used by Rails. Confirm that the application logs show a successful boot without printing credentials.

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

Deploy and operate the service

Restart in the right order

  1. Update or rotate the MongoDB secret in the deployment secret store.
  2. Confirm mongod is running and accepting authenticated connections.
  3. Restart the Rails process so Mongoid creates a pool with the current settings.
  4. Run the Rails ping and controlled read/write check.
  5. Exercise one normal application request and inspect both Rails and MongoDB logs for authentication or timeout errors.

Protect the data path

Monitor free disk space because MongoDB writes under /var/lib/mongodb by default. Keep Ubuntu and MongoDB packages patched from their supported repositories, retain logs long enough to diagnose failures, and test that backups can be restored to an isolated instance. A backup that has never been restored is an assumption, not a recovery plan.

Plan for growth

A single VPS is a straightforward starting point, but it leaves capacity, disk replacement, failover and recovery in your hands. Document the database size, expected traffic, backup schedule, restore procedure and the person responsible for each action before the application becomes business-critical.

Self-managed MongoDB versus a managed service

The Rails/Mongoid configuration is similar either way: the application still needs a URI, credentials and network access. The operational boundary changes.

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.
Decision area MongoDB on your VPS Managed MongoDB service
Operating responsibility You install packages, patch Ubuntu and MongoDB, manage systemd, inspect logs and handle disk capacity. The service operator handles the database hosts and much of the maintenance; you still manage application credentials and network policy.
Backups and recovery You choose backup tools, retention, encryption and restore testing. Backup and point-in-time options depend on the selected plan; verify retention and restore procedures before relying on them.
Network isolation Use localhost or a private interface plus your VPS firewall. Use the service’s private networking, IP allowlists and TLS requirements as documented for your account.
Authentication You create users, roles and rotation procedures and enable authorization in mongod.conf. The service supplies its own authentication workflow, but your Rails URI and secret handling remain your responsibility.
Scaling and failover You size the VPS and design replication, failover and upgrades. Available scaling and high-availability controls vary by service and region.
Regions and monthly cost Determined by your VPS provider, chosen size, storage and backups; no universal amount is established here. Varies by provider, region, storage, traffic and features; check current plan details directly.

Choose self-management when you need direct host control and can own patching, security and recovery. Choose a managed service when reducing database operations is worth its service limits and recurring cost. In both cases, keep MongoDB private, use least-privilege credentials and verify the Rails request path.

Troubleshooting guide

Symptom Likely cause What to check
Unit mongod.service could not be found The official repository was not added correctly or the package installation did not complete. Run apt-cache policy mongodb-org, confirm the Ubuntu codename and repository entry, then install the package again.
Service exits immediately Invalid YAML, wrong ownership, a full disk or a port conflict. Read sudo journalctl -u mongod; inspect /etc/mongod.conf, /var/lib/mongodb permissions, disk space and listeners on port 27017.
Connection refused on localhost mongod is stopped, bound to another address or listening on another port. Run systemctl status mongod, inspect the net section and verify the service log.
Authentication failed Wrong username, password, authentication database or URI encoding. Test with mongosh using the same credentials, confirm the user’s database and URL-encode reserved password characters.
Rails boots but database operations fail Mongoid loaded the wrong environment, the secret is absent from the Rails process or the user lacks readWrite. Run the Rails ping through the deployed service account, inspect the resolved environment name and test the application account directly.
Remote Rails host times out Private routing, bind address or firewall rules do not allow the application host. Confirm both VPSs can route privately, bind only to the intended private interface and allow port 27017 solely from the Rails address.
Works in SSH but not after reboot The service or Rails process is not enabled, or its environment is only present in your interactive shell. Check systemctl is-enabled mongod, the Rails process definition and its secret injection mechanism.

Deployment checklist

  • Ubuntu is an LTS release supported by the selected MongoDB version.
  • MongoDB came from its official repository, and mongod starts under systemd.
  • /var/lib/mongodb is available and owned by the service account.
  • Authentication and role-based access control are enabled before any non-local bind.
  • MongoDB listens only on localhost or a protected private interface.
  • The Rails user has application-level permissions, not administrative privileges.
  • config/mongoid.yml uses the correct environment and a secret-managed production URI.
  • A Rails ping and controlled read/write request succeed through the deployed process.
  • Backups, restore testing, patching, disk monitoring and credential rotation have named owners.

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 from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair 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.