Change MongoDB Default Port in Ubuntu/CentOS/Windows

MongoDB Server by default run on TCP port 27017. But you can change the mongodb port if you want.

In this tutorial I will explain How to change mongodb port on both Linux and Microsoft Windows Operating system.

Changing mongodb default port also changes the HTTP status interface port, which by default is 28017. The web status port is always available on a port that is X+1000, where X represents the server port.

Change MongoDB port on Linux/Ubuntu/CentOS

It is the same method for the All Linux distributions, including Ubuntu and CentOS 7. We need to change default port in MongoDB main configuration file, which is "/etc/mongod.conf".

Open the /etc/mongod.conf file and find the line that reads port: 27017:

port: 27017

And change the value to your new port number:

port: 20000

And restart mongod service:

sudo systemctl restart mongod.service

In CentOS you need to configure Selinux to allow new port if you have enabled Selinux:

sudo semanage port -a -t mongod_port_t -p tcp 20000

Change MongoDB Port on Windows

In windows, we need to add the new port number to the main configuration file under the net configuration option.

Following is the example of a mongod.cfg file in windows.

    destination: file
    path: c:\mongo\logs\mongod.log
    dbPath: c:\mongo\data
      serviceName: "MongoDB"
      displayName: "Mongo DB"
      description: "mongod service"
   port: 20000

When connecting to the mongo shell, mongo command by default use the default port 27017. If you changed the default port, then you need to use --port option of the mongo command.

mongo --port 20000

Just changing the default mongodb port does not reduce the risk much. In order to secure your database server, you need to allow only trusted clients to connect to the server using firewall settings.