MongoDB Replica Set

Instant MongoDB replica set for high availability and redundancy.

Deploy MongoDB Replica Set

mongo1

railwayapp-templates/mongo-replica-set

Just deployed

/data/db

mongo3

railwayapp-templates/mongo-replica-set

Just deployed

/data/db

mongo2

railwayapp-templates/mongo-replica-set

Just deployed

/data/db

Init Replica Set

railwayapp-templates/mongo-replica-set

Just deployed

This template deploys a MongoDB replica set for a more highly available and redundant data layer.

Inter-node communication

All communication between nodes is done over the private network.

Configuration tuning

To tune the configuration of the MongoDB nodes, refer to the MongoDB documentation or the documentation page in Docker Hub.

Authentication

The MongoDB replica set is deployed using keyfile authentication.

Connecting to the replica set

To connect to the replica set from another service in Railway, you should create a URI in the service's environment variables that includes all nodes. As an example:

MONGO_HOSTS=${{mongo1.RAILWAY_PRIVATE_DOMAIN}}:27017,${{mongo2.RAILWAY_PRIVATE_DOMAIN}}:27017,${{mongo3.RAILWAY_PRIVATE_DOMAIN}}:27017
REPLICA_SET_NAME=${{mongo1.REPLICA_SET_NAME}}
MONGO_URI=mongodb://${{mongo1.MONGO_INITDB_ROOT_USERNAME}}:${{mongo1.MONGO_INITDB_ROOT_PASSWORD}}@${{MONGO_HOSTS}}/?replicaSet=${{REPLICA_SET_NAME}}

With these variables set, you can then reference the MONGO_URI environment variable when configuring the client in your service code. You can find some examples here.

NOTE: If you need to connect to the set from your local machine, or from a service outside of the Railway project in which it is deployed, you will need to setup a tunnel into the Railway private network. Check out this tutorial for information on how to use Tailscale as a tunnel.

Template source

The source for this template can be found in the Railway Templates GitHub.

The MongoDB nodes are built almost directly from the official MongoDB image in Docker Hub, with the only customization being the setup of the Keyfile.

Resources


Template Content

More templates in this category

View Template
ReadySet
A lightweight caching engine for Postgres

View Template
Flare
A modern, lightning-fast file sharing platform built for self-hosting

View Template
EdgeDB
EdgeDB template based on their Docker deployment guide