MongoDB Docker容器启动失败:Failed to unlink socket file报错求助
I’ve run into this exact headache with MongoDB 3.6+ in Docker before—especially frustrating when you can’t even exec into the container to debug. The core issue here is that the MongoDB process inside the container doesn’t have permission to clean up the stale socket file left behind (either on the host’s /tmp or a mounted volume) after a server reboot. Here are Docker-specific solutions that should resolve this:
1. Use a Container-Internal Socket Path with tmpfs (Recommended)
The default /tmp directory is often mounted from the host, creating permission mismatches between the container’s mongodb user (UID 999 by default) and the host’s filesystem. Instead, configure MongoDB to use a socket path inside the container backed by tmpfs (a temporary in-memory filesystem that gets wiped on container restart):
For Docker Run:
docker run -d \ --name mongodb \ -v ./mongo-data:/data/db \ --tmpfs /var/run/mongodb:uid=999,gid=999,mode=0700 \ mongo:3.6 \ mongod --unixSocketPrefix /var/run/mongodb --unixSocketPermissions 0700
For Docker Compose:
Update your docker-compose.yml:
version: '3.8' services: mongodb: image: mongo:3.6 volumes: - ./mongo-data:/data/db tmpfs: - /var/run/mongodb:uid=999,gid=999,mode=0700 command: mongod --unixSocketPrefix /var/run/mongodb --unixSocketPermissions 0700 restart: unless-stopped
This setup creates a temporary directory owned by the container’s mongodb user, so the process can safely create and unlink the socket file without permission blocks.
2. Clean Up the Stale Socket File on the Host (Temporary Fix)
If you need a quick fix to get the container running immediately, check for the leftover socket file on your host and delete it:
sudo rm /tmp/mongodb-27017.sock
Then restart the container:
docker start mongodb
Note: This is a band-aid—you’ll likely hit the same issue after the next server reboot, so use this only while setting up the permanent fix above.
3. Use a Host-Mounted Directory with Correct Permissions
If you must keep the socket on the host (not recommended for most cases), create a dedicated directory and set its ownership to match the container’s mongodb UID/GID:
sudo mkdir -p /host/mongodb-socket sudo chown 999:999 /host/mongodb-socket
Then mount this directory into the container and configure MongoDB to use it:
docker run -d \ --name mongodb \ -v ./mongo-data:/data/db \ -v /host/mongodb-socket:/var/run/mongodb \ mongo:3.6 \ mongod --unixSocketPrefix /var/run/mongodb --unixSocketPermissions 0700
Why Regular Mongod Fixes Don’t Work Here
Most solutions you’ll find assume MongoDB is running directly on the host, where you can adjust user permissions or modify systemd service files. In Docker, the container-host isolation means the mongodb user inside the container doesn’t have the same permissions as host users—so cleaning up the socket from inside the container isn’t possible if it’s on a host-mounted volume.
内容的提问来源于stack exchange,提问作者Shady Mohamed Sherif

