I previously wrote my app using local development servers, and now that I have moved it onto an openshift small gear almost all works except for mysql connections.

In my code I have the line:

self.db = MySQLdb.connect(host, username, password, dbname)

When I review the openshift error log, the following error is reported:

_mysql_exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")

I think that python is trying to connect using a UNIX socket as opposed to an INET one, but I'm not sure how to change this behavior. Any help is much appreciated.

No correct solution


Not specific to MySQLdb: if you use localhost as hostname, a MySQL client using the MySQL C libraries will try to connect using UNIX socket (or named pipe on Windows). There are 2 ways around this, but you'll need to grant extra permissions to make it work for both:

Use IP address

Use IP address instead of the localhost hostname. This will make MySQL client connect using TCP/IP.

Use option files

The other way is to force the protocol using using option files. For example, in your ~/.my.cnf (or any file you want), add the following:


Now use the connection arguments to read the option file and group:

import MySQLdb
cnx = MySQLdb.connect(host='localhost', user='scott', passwd='tiger',

The group name does not need to be python, but it is good not to use mysql or client as it might interfere with other MySQL tools (unless you want that of course).

For setting up permissions, you'll need to use the IP address of localhost, something like:

mysql> GRANT SELECT TO yourdb.* TO 'scott'@'' IDENTIFIED BY ...;

(Site note: MySQL database drivers such as MySQL Connector/Python do not consider localhost to be special and connect through TCP/IP right away and you have to explicitly use the unix_socket.)

As I later discovered, while the database server runs on localhost, it runs on a very specific localhost bind address. In my case it was an address that I would never have though to try if I hadn't noticed how phpmyadmin was connecting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top