Search code examples
phpmysqlkubernetesgoogle-kubernetes-engineunix-socket

Connecting to a MySQL container in the same pod


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


Solution

  • 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.