MongoDB Replica Set Single-node deployment

In a post situation where you need to use a replica set but don’t want to use multiple nodes, you can use the following deployment.

configuration

Docker-compose deployment is simple and convenient. Here is the docker-comemage. yaml configuration,

version: "3"
services:
  main:
    image: Mongo: 4.4
    environment:
      MONGO_INITDB_ROOT_USERNAME: [Your Username]
      MONGO_INITDB_ROOT_PASSWORD: [Your Password]
    ports:
      - 27017: 27017
    Optional data mount
    volumes:
      - /data/mongo/db:/data/db
    restart: always
    entrypoint: [ "/usr/bin/mongod"."--auth"."--bind_ip_all"."--replSet"."rs0" ]

Copy the code

Points to note:

  • --authEnable authentication; otherwise, the database runs naked
  • --bind_ip_allAllow access to all or specified IP addresses--bind-ip
  • rs0Is the name of the replication set, which may be used when connecting

Use docker-comement-f [Your ‘docker-comse.yaml’ path] up-d

After the startup, enter Mongo Shell and initialize the cluster. After the initialization, check the cluster status. If the configuration is incorrect during the initialization, you can initialize the cluster again

Database validation

use admin;
db.auth('Username','Password')
Copy the code

Initializing a Cluster

Note host is the local address

Rs. initiate({_id: "rs0", version: 1, members: [{_id: 0, host: "127.0.01:27017"}]})Copy the code

Viewing Cluster Status

rs.status()
Copy the code

reinitialization

# in mongo shell, execute the following command line by line: rsconf = rs.conf(); rsconf.members = [{_id: 0, host: "localhost:27017"}]; rs.reconfig(rsconf, {force: true});Copy the code