Pomme.Verte
Pomme.Verte

Reputation: 1792

Docker container bash can't connect to local MySQL server through socket

It's a long title but it should be explicit enough.

If I run a docker container with bash and install mysql via apt-get install mysql-server the run the following command : mysql -u root -p

I'm met with a resounding :

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

Same goes with pretty much anything that is installed and uses the network.

Does this mean I should EXPOSE port 3306? What if that port is in use on the host (outside the container) but all the apps inside the container expect to call that port? i.e. : When I run the container while exposing 12345:3306 will the apps using the lo interface be expected to use port 3306 or 12345?

I find this part pretty confusing. Thanks!

Upvotes: 1

Views: 1170

Answers (1)

Corba the Geek
Corba the Geek

Reputation: 49

A MySQL Docker container isn't using the /var/run lock. Instead, try addressing the container directly by explicitly specifying its IP address.

First get the container's IP address. Something like this:

export MYSQL_IP_ADDRESS=$(sudo docker inspect --format="{{ .NetworkSettings.IPAddress }}" mysql_db)

where 'mysql_db' is the name you've given your MySQL Docker container.

You should be able to 'echo' your IP address:

corba@bilbovm01:~$ echo $MYSQL_IP_ADDRESS 
172.17.121.2

Then specify that host name on the command line:

mysql -h $MYSQL_IP_ADDRESS -u root -p

To answer your other question about port visibility, I assume you're using the standard mysql/mysql-server image from hub.docker.com. That image automatically exposes 3306, but you must start it with MYSQL_ROOT_HOST so that it allows you to connect to it from your host IP. For example, My host IP address is 172.17.121.1. So I would start my container like this:

corba@bilbovm01:~$ sudo docker run -d --name mysql -e MYSQL_ROOT_PASSWORD=blat -e MYSQL_ROOT_HOST=172.17.121.1 mysql/mysql-server:latest 
aa09bc5a30b8f84b68d760d828f8e451238405a177caef4ad802bef44ad43352
corba@bilbovm01:~$ mysql -h $MYSQL_IP_ADDRESS -u root -p 
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.17 MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Upvotes: 1

Related Questions