Skip to content
MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017

DodaTech 2 min read

The error “MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017” means your application tried to connect to MongoDB on localhost:27017 but the TCP connection was actively refused — no process is listening on that port.

What It Means

The MongoDB Node.js driver (or any MongoDB client) attempted to open a socket to 127.0.0.1 on port 27017. The operating system responded with “Connection refused” because nothing is accepting connections at that address and port combination.

Why It Happens

  • The mongod daemon is not running on the machine.
  • MongoDB is installed but the service failed to start or crashed.
  • MongoDB is listening on a different port or only on a Unix socket.
  • A firewall or security group is blocking port 27017.
  • MongoDB is bound to 127.0.0.1 but you are connecting from a different host.
  • The MongoDB process is running inside a container that is not port-mapped.

How to Fix It

1. Start the MongoDB service

sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

2. Verify MongoDB is listening

sudo ss -tlnp | grep 27017

Expected output shows mongod listening on 127.0.0.1:27017.

3. Check the MongoDB log for errors

sudo tail -100 /var/log/mongodb/mongod.log

4. Test the connection directly

mongosh --host 127.0.0.1 --port 27017

5. If running in Docker, expose the port

docker run -d -p 27017:27017 --name mongodb mongo:7

FAQ

How do I change the MongoDB default port?
Edit /etc/mongod.conf, change net.port to your desired value, then restart: sudo systemctl restart mongod. Update your application connection string to match the new port.
What does 'bindIp: 127.0.0.1' mean in mongod.conf?
It restricts MongoDB to listen only on the local loopback interface. To allow remote connections, change it to 0.0.0.0 or a specific IP address, then restart mongod.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro