In this MongoDB tutorial, I will explain how I managed to resolve the error “Failed to set up listener: socketexception: address already in use MongoDB”.
Socketexception: address already in use MongoDB
When I run the command mongod in my terminal I get the following error message:
From the error, It is clear that the address or port the MongoDB is trying to start from is already occupied with another instance or some other process.
You can either run the mongod instance in another port or kill the previous instance or the process whichever is using the port reserved for MongoDB instance to start.
We will discuss the following ways to fix this error.
Fix 1 — Kill the instance which is using the PORT reserved for mongo.
First, you have to search for a list of operations running on your machine by typing:
sudo lsof -iTCP -sTCP:LISTEN -n -P
And, then search for mongod command and its PID and type,
sudo kill <mongo_command_pid>
The above command will kill the mongod instance. After that, Start again your mongod instance by typing,
You can see MongoDB running successfully.
Also, check: MongoDB data directory /data/db not found
Fix 2 — Run mongo instance in another PORT.
In MongoDB, By default running port is 27017. And, you are already running a previous mongo instance in port 27017. So if you don’t want to disturb it then you can run the mongo instance in another port using the following command.
mongod — port 27018
Here, I have used 27018 to run the mongo instance, you can either use the following lists of the default TCP ports used by MongoDB:
|27017||This is the default port for mongod and mongos instances.|
|27018||It is the default port when running with –shardsvr runtime operation.|
|27019||It is the default port when running with –configsvr runtime operation.|
Also, read: Select the first element in an array in MongoDB
In short, we can say, we have to either run the mongod instance in another port or kill the previous instance or the process whichever is using the port reserved for MongoDB instance to start.
In this tutorial, we have covered the reason behind getting errors “MongoDB socketexception: address already in use” and fixed the error with two different solutions.
Also, take a look at some more tutorials on MongoDB.
- MongoDB compare two fields
- MongoDB get collection size
- Current date in MongoDB
- Display MongoDB data in HTML
- Distinct query in MongoDB
- MongoDB find string contains
After working for more than 15 years in the Software field, especially in Microsoft technologies, I have decided to share my expert knowledge of SQL Server. Check out all the SQL Server and related database tutorials I have shared here. Most of the readers are from countries like the United States of America, the United Kingdom, New Zealand, Australia, Canada, etc. I am also a Microsoft MVP. Check out more here.