8

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.

Felix Yan
  • 14,841
  • 7
  • 48
  • 61

3 Answers3

9

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.

Tyler Brock
  • 29,626
  • 15
  • 79
  • 79
7

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
Shane Davies
  • 940
  • 10
  • 10
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

Community
  • 1
  • 1
ukessi
  • 1,381
  • 1
  • 10
  • 15
  • 1
    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. – Felix Yan Dec 07 '11 at 09:13