9

Is there any way to connect to mongodb via unix socket in python, while the official pymongo module does not support unix socket yet.

I'd like any third-party alternatives, or patches, while I've searched around and did not find one.

I do not like an ORM-style library since the mongodb => python dicts are natural and easy to use, so I did not take something like MongoEngine into account.

3 Answers 3

10

MongoDB, by default, creates a unix socket at /tmp/mongodb-27017.sock. As of pymongo 2.4 you can make a connection like this:

from pymongo import MongoClient
CONNECTION = MongoClient('/tmp/mongodb-27017.sock')

Additionally you can disable this behavior by starting mongod with --nounixsocket or specify an alternate location with --unixSocketPrefix <path>

MongoDB will always create and listen on a UNIX socket, unless --nounixsocket is set, --bind_ip is not set, or --bind_ip specifies 127.0.0.1.

Sign up to request clarification or add additional context in comments.

2 Comments

So this was finally implemented since pymongo 2.4. Thank you!
Say, "as of pymongo 2.4". Is pymongo the one creating the unix socket? Or is it "...sock. As of pymongo 2.4, you can make a connection..."
8

Update for MongoDB v3.x

If you upgrade to MongoDB 3.x on linux, the group and other permissions on /tmp/mongodb-27017.sock have been removed. You will receive permission denied error's when you connect using MongoClient(host='/tmp/mongodb-27017.sock')

To fix this, upgrade your MongoDB configuration file to YAML format, which includes the filePermissions option so you set the permissions back.

Example /etc/mongod.conf in YAML format:

storage:
    dbPath: "/var/lib/mongodb"
systemLog:
    destination: file
    path: "/var/log/mongodb/mongod.log"
    logAppend: true
net:
    unixDomainSocket:
        filePermissions: 0777

Comments

1

Outside the scope of Python, you can build a proxy between TCP/IP socket and unix domain socket. So that, you can still use pymongo

Either netcat or socat can do this.

nc -l 1234 | nc -U /tmp/foo

or

socat TCP-LISTEN:1234,reuseaddr,fork UNIX-CLIENT:/tmp/foo

See also:

Redirecting TCP-traffic to a UNIX domain socket under Linux

1 Comment

Thank you anyway, but this is not exactly what I want :) I want to use unix socket for performance and stability, but if I build a proxy in TCP and forwards queries the two goals are all missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.