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,
mongod
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:
Default Port | Description |
---|---|
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
Conclusion
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
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.