Troubleshooting MongoDB Socket Connection Refused on CentOS Stream / Rocky Linux (Port 27017)
Fix 'MongoDB socket connection failed connection refused port 27017' on CentOS Stream/Rocky Linux. Resolve firewall, service status, or configuration issues efficiently.
Fix 'MongoDB socket connection failed connection refused port 27017' on CentOS Stream/Rocky Linux. Resolve firewall, service status, or configuration issues efficiently.
When your application fails to connect to MongoDB, presenting a "socket connection failed connection refused" error, it signifies that the connection attempt was actively denied by the target machine, rather than simply timing out. This is a common and often straightforward issue to diagnose on CentOS Stream or Rocky Linux environments, typically pointing to the MongoDB service itself, network configuration, or system security policies.
Symptom & Error Signature
Users will typically experience their applications failing to connect to the MongoDB database. This can manifest as blank pages, error messages displayed in the application UI, or system-level connection errors when attempting to use the mongo shell or other MongoDB client tools.
Common error messages you might encounter include:
From a MongoDB client (e.g., mongo shell):
MongoDB shell version v5.0.x
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Error: connect ECONNREFUSED 127.0.0.1:27017
Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:372:17
@(connect):2:6
exception: connect failed
exiting with code 1
From an application log (example for Node.js using Mongoose):
MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at _handleConnectionErrors (/path/to/node_modules/mongoose/lib/connection.js:770:11)
at Connection.openUri (/path/to/node_modules/mongoose/lib/connection.js:745:11)
at Mongoose.connect (/path/to/node_modules/mongoose/lib/index.js:347:15)
at Object.<anonymous> (/path/to/your/app.js:20:8) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) { '127.0.0.1:27017' => ServerDescription { address: '127.0.0.1:27017', type: 'Unknown',
errors: [ [MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27017] ],
roundTripTime: -1,
lastUpdateTime: 1678886400000,
lastWriteDate: 0,
minWireVersion: 0,
maxWireVersion: 0,
maxProtoMsgSize: 0,
hosts: [],
passives: [],
arbiters: [],
tags: {},
electionId: null,
primary: null,
me: null,
'$clusterTime': null } },
stale: false,
compatible: true,
heartbeatIntervalMS: 10000,
localThresholdMS: 15,
setName: null,
maxElectionId: null,
maxSetVersion: null,
commonWireVersion: null,
logicalSessionTimeoutMinutes: null
}
}
System-level check (if MongoDB isn't listening):
$ sudo ss -tulnp | grep 27017
# (No output indicates nothing is listening on port 27017)
Root Cause Analysis
A "connection refused" error typically means a network packet reached the target machine, but no process was listening on the specified port (27017 in this case), or an explicit rule denied the connection. For MongoDB on CentOS Stream/Rocky Linux, the primary causes are:
- MongoDB Service Not Running: The
mongoddaemon is either stopped, failed to start, or crashed. This is the most common reason. - Incorrect Listen Address (bindIp): MongoDB is configured to listen only on
localhost(127.0.0.1), but the client application is attempting to connect from a different IP address (e.g., from another server or a specific network interface IP). Conversely, it might be configured to listen on an IP that is no longer valid or accessible. - Firewall Blockage (
firewalld): The operating system's firewall (firewalldon CentOS/Rocky Linux) is blocking incoming connections to port 27017. - SELinux Policy Violation: SELinux (Security-Enhanced Linux) is preventing the
mongodprocess from binding to the port, accessing its data files (/var/lib/mongo), or log files (/var/log/mongodb). - Resource Exhaustion or Corruption: Less common for a "connection refused" (more often causes service failure), but issues like full disk space, corrupted data files, or incorrect permissions can prevent the
mongodservice from starting successfully.
Step-by-Step Resolution
Follow these steps sequentially to identify and resolve the root cause of the connection refused error.
1. Verify MongoDB Service Status
The first step is always to check if the MongoDB service is running and healthy.
sudo systemctl status mongod
Expected Output (Running):
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Thu 2026-10-22 10:30:00 UTC; 5min ago
Docs: https://docs.mongodb.org/manual
Main PID: 1234 (mongod)
Memory: 100.0M
CPU: 1.5s
CGroup: /system.slice/mongod.service
└─1234 /usr/bin/mongod --config /etc/mongod.conf
...
If the service is not running (inactive (dead)) or has failed (failed):
Start the service:
sudo systemctl start mongod
If it fails to start or immediately stops, check the service logs for specific error messages:
sudo journalctl -xeu mongod
Look for messages indicating file permissions issues, configuration syntax errors, or disk space problems.
Common log errors include:
Failed to start MongoDB Database Server.ERROR: dbpath (/var/lib/mongo) does not exist.(Create it withsudo mkdir -p /var/lib/mongo && sudo chown -R mongod:mongod /var/lib/mongo)ERROR: Cannot create/open lock file(Permissions issue).YAML: bad expression(Configuration syntax error).
2. Check MongoDB Configuration (Listen Address)
MongoDB's configuration file, typically /etc/mongod.conf, specifies which IP addresses it should listen on. If your application is on a different machine or connecting via a specific network interface, ensure MongoDB is listening on the correct IP.
Open the configuration file:
sudo vi /etc/mongod.conf
Look for the net: section and the bindIp or bindIpAll directives:
# mongod.conf
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1 # Listen on localhost only
# bindIp: 0.0.0.0 # Listen on all network interfaces
bindIp: 127.0.0.1: MongoDB will only accept connections from the local machine (localhost). If your application is on a different server or in a Docker container trying to reach the host's IP, this will cause a "connection refused" error.bindIp: <your_server_ip>: If your server has multiple IP addresses, ensure this is the correct IP that your client is trying to connect to.bindIp: 0.0.0.0: MongoDB will listen on all available network interfaces. This is generally required for remote connections.
Setting
bindIp: 0.0.0.0without proper firewall rules is a significant security risk, as it exposes your MongoDB instance to the public internet. Always combine this with robust firewall rules to restrict access to trusted IPs only.
If you modify mongod.conf, save the changes and restart the MongoDB service:
sudo systemctl restart mongod
sudo systemctl status mongod
3. Inspect Firewall Rules (firewalld)
CentOS Stream and Rocky Linux use firewalld by default. It's common for firewalld to block incoming connections to non-standard ports.
First, check the active firewall rules:
sudo firewall-cmd --list-all
Look for port 27017/tcp in the ports: section of your active zone (usually public). If it's not listed, you need to add it.
To allow TCP connections on port 27017 permanently:
sudo firewall-cmd --permanent --add-port=27017/tcp
Reload the firewall to apply the changes:
sudo firewall-cmd --reload
If you need to restrict access to only specific IP addresses, use the
--add-rich-ruledirective for enhanced security:sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="YOUR_CLIENT_IP/32" port port="27017" protocol="tcp" accept' sudo firewall-cmd --reloadReplace
YOUR_CLIENT_IPwith the actual IP address of your application server or client machine.
After modifying firewall rules, re-check sudo firewall-cmd --list-all to confirm the change.
4. Review SELinux Status and Policies
SELinux can prevent mongod from starting, binding to its port, or accessing its data/log directories, even if file permissions seem correct.
Check SELinux status:
sestatus
And its enforcement mode:
getenforce
If getenforce returns Enforcing, SELinux might be the cause.
Temporary Test (Not Recommended for Production):
You can temporarily disable SELinux to see if it resolves the issue.
sudo setenforce 0
Then try to start MongoDB and connect. If it works, SELinux is indeed the problem. Remember to re-enable it:
sudo setenforce 1
Disabling SELinux (
setenforce 0) compromises system security. Only use this for temporary diagnosis, never leave it disabled in a production environment.
Permanent SELinux Resolution:
Check for SELinux Audit Logs: Look for recent denials related to
mongodin the audit logs.sudo ausearch -c 'mongod' -ts recentIf you find denials, you can generate a custom SELinux policy module:
sudo ausearch -c 'mongod' --raw | audit2allow -M my-mongod sudo semodule -i my-mongod.ppVerify Port Context: Ensure that the MongoDB port (
27017) has the correct SELinux typemongod_port_t.sudo semanage port -l | grep 27017If it's missing or has an incorrect type, add or modify it:
# If the port context is missing: sudo semanage port -a -t mongod_port_t -p tcp 27017 # If it's already defined with another type and needs modification: # sudo semanage port -m -t mongod_port_t -p tcp 27017Correct File Contexts: Ensure MongoDB's data and log directories have the correct SELinux context.
sudo semanage fcontext -a -t mongod_var_lib_t "/var/lib/mongo(/.*)?" sudo semanage fcontext -a -t mongod_log_t "/var/log/mongodb(/.*)?" sudo restorecon -Rv /var/lib/mongo /var/log/mongodbAnd also for the configuration file:
sudo semanage fcontext -a -t mongod_etc_t "/etc/mongod.conf" sudo restorecon -Rv /etc/mongod.conf
After applying SELinux changes, restart MongoDB:
sudo systemctl restart mongod
5. Check Disk Space and Permissions
While less likely to directly cause "connection refused," a full disk or incorrect permissions can prevent mongod from starting.
Check Disk Space:
df -h
Ensure there's enough free space on the partition hosting /var/lib/mongo and /var/log/mongodb.
Check Permissions:
MongoDB runs as the mongod user. Ensure its data and log directories are owned by this user and group.
ls -ld /var/lib/mongo /var/log/mongodb
Expected output:
drwxr-xr-x. 5 mongod mongod 4.0K Oct 22 10:30 /var/lib/mongo
drwxr-xr-x. 2 mongod mongod 4.0K Oct 22 10:30 /var/log/mongodb
If permissions are incorrect, reset them:
sudo chown -R mongod:mongod /var/lib/mongo
sudo chown -R mongod:mongod /var/log/mongodb
Then try restarting MongoDB.
sudo systemctl restart mongod
6. Test Connectivity
After performing any of the above troubleshooting steps, always test connectivity.
From the MongoDB server itself:
mongo --host 127.0.0.1 --port 27017
Or, for a quick network check:
telnet 127.0.0.1 27017
# Or using netcat:
nc -zv 127.0.0.1 27017
A successful telnet or nc connection will show a connected message and then usually a blank screen (for telnet) or "Connection to 127.0.0.1 27017 port [tcp/mongod] succeeded!" (for nc). If it returns "Connection refused," continue troubleshooting.
From a remote client (if applicable):
mongo --host <Your_Server_IP> --port 27017
telnet <Your_Server_IP> 27017
nc -zv <Your_Server_IP> 27017
If local connectivity works but remote does not, focus on firewall (firewalld) and MongoDB's bindIp configuration.
Our Production Verification Guarantee
Encountering a bug not covered here or running a non-standard kernel configuration? Our solutions are continually refined against real production incidents. Submit an environment trace for our editorial team to replicate.