As you might have observed, after starting the MongoDB server, the mongod process binds to all interfaces which may not be suitable for all use cases. For example, if you are using MongoDB for development or you are running a single node instance on the same server as your application, you probably do not wish to expose MongoDB to the entire network. You might also have a server with multiple network interfaces and may wish to have MongoDB server listen to a specific network interface. In this recipe, we will see how to start MongoDB on a specific interface and port.
Binding MongoDB process to a specific network interface and port
Getting ready
Make sure you have MongoDB installed on your system as shown in the previous recipes.
How to do it...
- Find your system's network interfaces and corresponding IP address(s) using the ifconfig command. For example, let's assume your system's IP address is 192.168.1.112.
- Start the mongod daemon without any special flags:
mongod --dbpath /data/db
This starts the mongod daemon which binds to all network interfaces on port 27017.
- In a separate Terminal, connect to your MongoDB server on this IP:
mongo 192.168.1.112:27017
You should see a MongoDB shell.
- Now stop the previously running mongod daemon (press Ctrl + C in the Terminal) and start the daemon to listen to your loopback interface:
mongod --dbpath /data/db --bind_ip 127.0.0.1
- In a separate Terminal, connect to your MongoDB server on this IP:
mongo 192.168.1.112:27017
- This time the mongo client will exit with a connect failed message. Let's connect to your loopback IP and it should work:
mongo 127.0.0.1:27017
- Stop the mongod daemon (press Ctrl + C in the Terminal) and let's start the daemon such that it binds to a different port as well:
mongod --dbpath /data/db --bind_ip 127.0.0.1 --port 27000
- In a separate Terminal, connect to your MongoDB server on this IP:
mongo 127.0.0.1:27000
- You should be connected to the server and see the mongo shell.
How it works...
By default, the mongod daemon binds to all interfaces on TCP port 27017. By passing the IP address with the --bind_ip parameter, we instructed mongod daemon to listen only on this socket. Next we passed the --port parameter along with --bind_ip to instruct the mongod daemon to listen to a particular port and IP. Using a non-standard port is a common practice when one wishes to run multiple instances of mongod daemon (along with a different --dbpath) or wish to add a little touch security by obscurity. Either way, we will be using this practice in our later recipes to test shards and replica sets setups running on a single server.