How to change the port of the MongoDB server

Hi All,

We are using MongoDB as database server in our project and our MongoDB production server is hosted on a public server with public IP. Due to security reason I need to change the default port of MongoDB server from 27017 to port of my choice (Lets say 8080). Can someone give me steps to do this. More than one option to change the port of MongoDB server will be great help.

Thanks in advance !!

Posted by Andy on 2015-03-28 07:11:14.0


Hi Andy ,

By default , MongoDB runs on the port : 20717 . You can change the port as shown below. 

Solution : How to change the port of the MongoDB server

There are two ways in which the default port for MongoDB can be changed :

Note : My installation folder is-   "E:\mongodb"

Method I : Starting MongoDB server with --port argument

Step 1 :  Right click on cmd.exe , and click on Run as administrator

Step 2 : In your MongoDB directory structure , navigate to bin folder and type the command as per the following screenshot.
   Port number can be of your choice.
 
cmd port
 
 

Step 3 : You would get the following message in the command prompt
waiting for connections on port 20000
Now , open another command prompt window( cmd.exe ⇒ Run as administrator) and navigate to the bin folder.

Note : Do not close the window where the server is waiting for connections.

Step 4 : You would need to start an instance of MongoDB specifying the port number again as shown below 
 
cmd port

The connection is accepted . MongoDB now runs on the port number of your choice!


Method II : Changing the port number in the configuration file

Step 1 : Create a configuration fileIn order to do this , open a text editor ( I use notepad++ ) and type configuration settings as per the following screenshot:
 
mongo config file

Note : The config file is in YAML format. It does not accept tabs, use spaces instead. Sample config files can be found here.
Save the notepad file as mongodb.conf inside the etc folder.

Step 2 : Start MongoDB with --config argument as shown below
 
mongo cmd config

Follow up with Step 3 and Step 4 of Method I .

MongoDB now runs on port of your choice ! 
Hope this helps.

Cheers!!

Posted by Pathania on 2015-05-14 07:43:58.0