Connecting to a MySQL container in the same pod

2/3/2016

Good day,

I am using Kubernetes to run containers on the google container engine.

The idea is to run two containers in a pod. One container uses the docker mysql image, the other runs php, laravel, nginx and composer.

Locally, this works. The idea is that the php can connect to the database on localhost, and this should work if both containers are in the same pod. However, when the pod is launched, we see the following message in the log:

SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

The only difference is that when testing locally, I change localhost to the internal docker ip.

Thanks and good day

-- Joren
google-kubernetes-engine
kubernetes
mysql
php
unix-socket

2 Answers

2/4/2016

MySQL comes preconfigured to only support named pipe connections on the localhost, if you are going to connect to it from another logical machine you need to locate the following line in your my.cnf file...

#bind-address = 127.0.0.1

and replace it with...

bind-address = {your network ip here}

Once you have enabled the bind address restart your mysql server, check the error log to ensure that no exceptions occurred with binding the address, and then login as root and create a new user account attached to that ip address which you can then use to access MySQL from any other logical machine as long as you connect to it using the IP address you defined in my.cnf.

Please note by default the root account is only accessible from the localhost so you will either need to create a new user account or alter the root account to support remote connections (not secure)

-- Chris Rutherfurd
Source: StackOverflow

2/6/2016

On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option. For example:

shell> mysql --host=127.0.0.1
shell> mysql --protocol=TCP

The --protocol option enables you to establish a particular type of connection even when the other options would normally default to some other protocol.

The other solution is using Kubernetes Volume abstraction to share a path between containers. Edit /etc/mysql/my.cnf on both containers' images and change socket location for both MySQL server and client to point to the shared directory or disk.

-- Kamran
Source: StackOverflow