1

I have a project developed with PHP and MySql.

When I Use the connection to DB I set the connection as a follow:

 // Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];


/* -------------------------------- CONNESSIONE -------------------------------------- */
$servername = "localhosto";
$username_db = "xxxxxx";
$password_db = "yyyyyy";
$db = "zzzzzz";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$db", $username_db, $password_db);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //echo "Connected successfully<br/><br/>";
}
catch(PDOException $e)
{
    echo "Connection failed: " . $e->getMessage()."<br/><br/>";
}

the project run correctly and connect to MySql without problems.

Next step I was created a Docker Image with a follow docker file:

FROM php:7.0-apache


RUN apt-get update \
  && apt-get install -y --no-install-recommends libpq-dev \
  && docker-php-ext-install mysqli pdo_pgsql pdo_mysql


COPY / /var/www/html
EXPOSE 80

I have create the image and container:

docker build -t mysoftware C:\Users\mysoftware
docker run -d -p 5000:80 mysoftware

but the Php application don't connect to MySql.

I need to change the connection with the name of server:

$servername = "SERVER_NAME";

Why I have an error if the app run correcly without container ??

daniele3004
  • 13,072
  • 12
  • 67
  • 75

2 Answers2

2

When running inside the container, localhost will not resolve to the host machine, rather it will refer to the container IP address.

You need to connect to the host machine from within the container. For that check: From inside of a Docker container, how do I connect to the localhost of the machine?

yamenk
  • 46,736
  • 10
  • 93
  • 87
1

(Assuming *nix) Once you have the mysql docker container running...

docker ps

and find the name of the mysql container that is running. Then to find the IP address...

docker inspect <name_of_container> | grep IPAddress

Then use this IP address for the server to connect to.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55