Troubleshooting MongoDB ‘Connection Refused’ on Alpine Linux (Port 27017)
Fix MongoDB socket connection failed and 'Connection Refused' errors on Alpine Linux. Learn to diagnose and resolve port 27017 issues in native and Docker environments.
Fix MongoDB socket connection failed and 'Connection Refused' errors on Alpine Linux. Learn to diagnose and resolve port 27017 issues in native and Docker environments.
Introduction
Encountering a "MongoDB socket connection failed connection refused port 27017" error on an Alpine Linux environment can be a critical roadblock for applications relying on the database. This error signifies that your client application or mongo shell was unable to establish a TCP/IP connection to the MongoDB server process on the specified port, indicating that no process was listening on that address:port combination or a network-level blockage prevented access. This guide will walk you through the precise steps to diagnose and resolve this common issue, applicable whether MongoDB is running directly on Alpine or within a Docker container.
Symptom & Error Signature
When MongoDB is inaccessible due to a "connection refused" error, client applications will typically report an inability to connect to the database. You might see variations of the following error messages in application logs, when attempting to connect with the mongo shell, or within service startup logs.
From mongo shell:
MongoDB shell version vX.Y.Z
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:374:17
@(shell):1:6
exception: connect failed
From application logs (e.g., Node.js, Python, Java):
Error: MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
at _handleConnectionErrors (/path/to/node_modules/mongoose/lib/connection.js:770:11)
at NativeConnection.openUri (/path/to/node_modules/mongoose/lib/connection.js:745:11)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at Connection.Object.<anonymous>.Connection.openUri (/path/to/node_modules/mongoose/lib/connection.js:1:380)
During MongoDB service startup on Alpine (if it fails):
/etc/init.d/mongodb: ERROR: mongodb failed to start
Root Cause Analysis
A "connection refused" error, as opposed to a "connection timed out," typically indicates that the target machine was actively rejecting the connection attempt. This means the TCP handshake could not be completed. The most common underlying reasons for this on Alpine Linux are:
- MongoDB Service Not Running: The
mongodprocess is simply not active on the server. - Firewall Blocking Port 27017: An
iptablesrule on the server (or host if in Docker) is preventing incoming connections to port 27017. - Incorrect
bindIpConfiguration: MongoDB is configured to listen only onlocalhost(127.0.0.1) while the client is attempting to connect from a different IP address. - Resource Constraints: The server lacks sufficient RAM, disk space, or open file descriptors for MongoDB to start or operate correctly.
- Incorrect Data Directory Permissions: The
dbpath(data directory) has incorrect permissions or ownership, preventingmongodfrom starting. - Port Conflict: Another process is already using port 27017.
- Docker-Specific Issues:
- The Docker container running MongoDB is not running.
- The host port 27017 is not correctly mapped to the container's port 27017.
- Network configuration issues between containers or from the host to the container.
- Corrupted
mongod.lockFile: A previous unclean shutdown might leave a lock file preventing a new instance from starting.
Step-by-Step Resolution
Follow these steps meticulously to diagnose and resolve the MongoDB connection issue on Alpine Linux.
#### 1. Verify MongoDB Service Status
The first and most common reason for "connection refused" is that the MongoDB server process (mongod) is not running.
A. If MongoDB is installed directly on Alpine Linux (OpenRC service):
Check the service status:
sudo rc-service mongod status
If it's not running, try to start it:
sudo rc-service mongod start
Then check the status again. If it fails to start, examine the MongoDB logs (see step 2).
B. If MongoDB is running inside a Docker container:
Verify the container status:
docker ps -a | grep mongo
Look for a container with "mongo" in its name or image and check its STATUS. It should be Up .... If it's Exited or not listed, start it:
docker start <your_mongodb_container_name_or_id>
If it fails to start or immediately exits, check its logs:
docker logs <your_mongodb_container_name_or_id>
#### 2. Examine MongoDB Log Files
MongoDB logs are crucial for understanding why the service might not be starting or why it's refusing connections.
A. For native Alpine installation:
The default log path for MongoDB on Alpine is typically /var/log/mongodb/mongod.log or specified in /etc/mongod.conf.
sudo tail -f /var/log/mongodb/mongod.log
Look for errors like:
Failed to start up WiredTiger under any compatibility version.(often due to corrupted data)Error creating IP socket listener: Operation not permitted(permission issue or port conflict)Failed to unlink socket file /tmp/mongodb-27017.sock(old socket file)
B. For Docker container:
docker logs <your_mongodb_container_name_or_id>
Review the output for any errors during startup.
A common issue for startup failures in logs is insufficient memory, especially with WiredTiger storage engine (the default since MongoDB 3.2). Ensure your system or Docker container has at least 512MB-1GB of RAM allocated.
#### 3. Verify mongod.conf bindIp and port Configuration
The mongod.conf file dictates how MongoDB listens for connections. The bindIp setting is particularly critical.
A. Locate and edit mongod.conf:
- Native Alpine: Typically
/etc/mongod.confor/etc/mongodb.conf. - Docker: If using a custom image, it might be baked in. For official images, you might pass configuration via command line arguments or a custom
mongod.confmounted as a volume. Access the running container's shell to check:docker exec -it <your_mongodb_container_name_or_id> cat /etc/mongod.conf
Open the configuration file for editing:
sudo vi /etc/mongod.conf # or wherever your config is located
Look for the net: section:
net:
port: 27017
bindIp: 127.0.0.1
B. Adjust bindIp:
If
bindIpis set to127.0.0.1and your client is connecting from a different IP (e.g., from another server or a Dockerized application connecting to the host's IP), you need to change it.To allow connections from any IP address (use with caution, and preferably behind a firewall):
net: port: 27017 bindIp: 0.0.0.0Alternatively, specify a list of allowed IP addresses or network interfaces:
net: port: 27017 bindIp: 127.0.0.1,<your_server_ip>,<other_allowed_ip>Replace
<your_server_ip>and<other_allowed_ip>with actual IPs.Ensure the
portis indeed 27017 unless you've intentionally configured it otherwise.
Setting
bindIp: 0.0.0.0allows MongoDB to listen on all network interfaces, making it publicly accessible. This is a major security risk. Always ensure your firewall is configured correctly to restrict access to trusted IP addresses only, especially for production environments.
After modifying mongod.conf, restart the MongoDB service:
- Native Alpine:
sudo rc-service mongod restart - Docker:
docker restart <your_mongodb_container_name_or_id>(or stop and start if it's exiting)
#### 4. Check Firewall Rules (iptables)
Even if MongoDB is running and configured correctly, a firewall can block incoming connections. Alpine Linux typically uses iptables.
A. List existing iptables rules:
sudo iptables -L -n -v
Look for rules that might be blocking port 27017 (e.g., REJECT or DROP rules on the INPUT chain).
B. Allow incoming traffic on port 27017:
To open port 27017 for specific IP addresses (recommended):
sudo iptables -A INPUT -p tcp --dport 27017 -s <trusted_client_ip> -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 27017 -j DROP # This drops all other connections to 27017 if you haven't explicitly allowed them
Replace <trusted_client_ip> with the actual IP address of your client application.
To temporarily open port 27017 for all incoming connections (for testing, not recommended for production):
sudo iptables -A INPUT -p tcp --dport 27017 -j ACCEPT
iptablesrules are typically volatile and will be lost on reboot unless saved. On Alpine, you'd userc-service iptables saveor similar methods depending on your setup (e.g.,/etc/network/if-pre-up.d/iptablesscript, or Docker's host firewall configuration). Ensure permanent rules are configured.
#### 5. Check Data Directory Permissions and Lock File
MongoDB requires specific permissions for its data directory (dbpath) and can sometimes get stuck due to a mongod.lock file from an unclean shutdown.
A. Identify dbpath:
Check your mongod.conf for the storage.dbPath setting. Common paths are /var/lib/mongodb or /data/db.
B. Check permissions and ownership:
Ensure the mongodb user (or the user running mongod) has read/write permissions on the dbpath.
sudo ls -ld /var/lib/mongodb # Replace with your actual dbpath
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chmod -R 700 /var/lib/mongodb
C. Remove mongod.lock (if present and after verifying mongod is not running):
If MongoDB crashed or didn't shut down cleanly, a mongod.lock file might be present in the dbpath. This prevents a new mongod instance from starting.
Only remove
mongod.lockif you are absolutely sure MongoDB is not running. Removing it while MongoDB is active can lead to data corruption.
sudo rm /var/lib/mongodb/mongod.lock # Replace with your actual dbpath
After these steps, try starting MongoDB again.
#### 6. Verify Docker Port Mapping and Networking
If you're using Docker, the connection issue might stem from incorrect port mapping or network configuration.
A. Check Docker Port Mapping:
When running the container, ensure port 27017 is correctly mapped from the host to the container. Look at the PORTS column in docker ps:
docker ps
You should see something like 0.0.0.0:27017->27017/tcp or 127.0.0.1:27017->27017/tcp. If not, your docker run command needs correction.
Example of correct docker run command:
docker run -d -p 27017:27017 --name mongodb_container mongo:latest
B. Check Docker Network (for multi-container setups):
If your application is in another Docker container, ensure both containers are on the same Docker network.
docker network ls
docker network inspect <your_docker_network_name>
If they are not, create a custom network and connect both containers to it:
docker network create my-app-network
docker run -d --network my-app-network --name mongodb_container mongo:latest
docker run -d --network my-app-network --name my-app-container my-app-image
Your application should then connect to mongodb_container:27017 as the host.
#### 7. Check System Resources and ulimit
Lack of system resources can prevent MongoDB from starting or accepting connections.
A. Disk Space:
Ensure there's enough free disk space for MongoDB's data files.
df -h
B. RAM:
MongoDB, especially with WiredTiger, can be memory-hungry. If your Alpine VM or container has very little RAM, it might fail.
free -h
C. Open File Descriptors (ulimit):
MongoDB requires a significant number of open file descriptors. The default ulimit on some systems can be too low.
Check current limits:
ulimit -n
If it's below 64000 (MongoDB's recommended minimum), you'll need to increase it.
Native Alpine: Edit
/etc/security/limits.conf(ifpam_limitsis in use, which might not be default on Alpine formongod's service file) or the OpenRC service script/etc/init.d/mongodto setulimit -n 64000beforemongodstarts. A common way is to add to/etc/sysctl.conf:fs.file-max = 100000Then
sudo sysctl -p. And for the service itself, you might need to modify the OpenRC init script to includeulimit -n 64000for themongoduser.Docker: You can pass
ulimitsettings to the container:docker run -d -p 27017:27017 --name mongodb_container --ulimit nofile=64000:64000 mongo:latest
Restart MongoDB after making ulimit changes.
By systematically going through these steps, you should be able to identify and resolve the "MongoDB socket connection failed connection refused port 27017" error on your Alpine Linux environment.