0

Running VirtualBox with Ubuntu 16.04 on which I have a Docker container that has Apache2 and PHP installed.

MYSQL is installed on the host(ubuntu on VirtualBox).

I am trying to access the MYSQL server on host from the docker container

<?php
$host = '192.168.136.101';
$user = 'root';
$pass = '****';
$db = 'test';
$port = '3306';

$con = mysqli_connect($host,$user,$pass,$db,$port);

// Check connection
if (mysqli_connect_errno())
{
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

?>

I get a connection refused notice.

when starting the container I have tried

docker run -ti -p 80:80 -p 3306:3306 IMAGE 

Which doesn't work as port 3306 is being used by MYSQL server on host and if I stop MYSQL server on host the docker run command executes however I am then unable to start MYSQL service on host

I have also tried

docker run -ti -p 80:80 --add-host=database:192.168.136.101 IMAGE

and changed the bind address in /etc/mysql/mysql.conf.d/mysqld.cnf accordingly

still no luck

Thanks

succeed
  • 834
  • 1
  • 11
  • 28
  • 1
    Below post might help. http://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach – YYY Dec 02 '16 at 11:36

1 Answers1

1

You will need to use the host network when running your container :

docker run -ti -p 80:80 --net="host" IMAGE 

Then, you can reference your database with localhost :

<?php
$host = '127.0.0.1';
$user = 'root';
$pass = '****';
$db = 'test';
$port = '3306';

You can also use the --net="bridge" option, which the default, instead of "host", but in that case you need to find out your host's IP, and configure Mysql to listen to the container's ip in the file my.cnf :

bind-address = x.y.z.u

where x.y.z.u is your container's IP.

Hakro
  • 2,625
  • 1
  • 12
  • 23
  • when binding the container IP address to my.cnf's bind address MYSQL server does not start giving the error notice 'Job for mysql.service failed because the control process exited with error code. See "systemctl status mysql.service" and "journalctl -xe" for details' – succeed Dec 02 '16 at 19:22
  • Sorry it does work! From host enter sudo ip addr show docker0 – succeed Dec 02 '16 at 19:32
  • Whereas before I was using the IP address obtained from ifconfig when run from container – succeed Dec 02 '16 at 19:43