Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 439
Joren Avatar asked Feb 03 '16 15:02

Joren


People also ask

How do containers in the same pod communicate?

Multiple containers in the same Pod share the same IP address. They can communicate with each other by addressing localhost . For example, if a container in a Pod wants to reach another container in the same Pod on port 8080, it can use the address localhost:8080 .

Can one pod have multiple containers?

The primary reason that Pods can have multiple containers is to support helper applications that assist a primary application. Typical examples of helper applications are data pullers, data pushers, and proxies. Helper and primary applications often need to communicate with each other.


1 Answers

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.

like image 197
Kamran Avatar answered Sep 22 '22 17:09

Kamran