Docker with PHP and MySql - $servername Error [duplicate] - php

This question already has answers here:
From inside of a Docker container, how do I connect to the localhost of the machine?
(41 answers)
Closed 5 years ago.
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 ??

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?

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

Related

docker container can't connect to localhost mysql server

im new to docker, have tried to setup my docker php-apache container to connect to mysql db running on my localhost. i created my docker image as follows:
dockerfile:
FROM php:7.2-apache
RUN docker-php-ext-install mysqli
build new docker image:
docker build -t will-php-env .
my php application is placed in my home folder(/home/will/php/)
i run my container as follows:
sudo docker run -it -p 180:80 -v "$PWD":/var/www/html will_php_env
the code for connection is:
mysqli_real_connect( mysqli_init(),"192.168.1.17", "root", "password", "bugtracker" );
error:
Warning: mysqli_real_connect(): (HY000/1045): Access denied for user 'root'#'172.17.0.2' (using password: YES) in /var/www/html/mantisbt-2.19.0/will.php on line 3
by the way, i will be able to connect to mysql server from the same container if i use the following code:
<?php
$will2k = new mysqli("192.168.1.17", "gkeepa", "password", "php");
please let me know why the container is not able to connect to mysql server on my localhost using mysqli_real_connect. thanks in advance

PHP PDO : SQLSTATE[HY000] [2002] Connection refused

I ran into this Problem with the PHP Data Object.
I cannot connect to my Database. First here is my PHP Script:
<?php
$serverName = "127.0.0.1";
$port = "3306";
$dbName = "callitTime";
$userName = "root";
$password = "superstrongPassword";
try {
$db = new PDO("mysql:host=$serverName;dbname=$dbName;port=$port;",
$userName, $password);
} catch (PDOException $pdoE) {
echo 'An Error occurred: ' . $pdoE->getMessage();
}
?>
I am using:
PHP 7.1.16
Nginx 1.13.12-1
MySQL 8.0.11-1debian9
All as Docker Containers.
A phpinfo() tells me that PDO Drivers are loaded as follows:
PDO Drivers:
sqlite
mysql
Driver Versions:
mysqlnd 5.0.12-dev
SQLite Library 3.15.1
I get the Error:
An Error occurred: SQLSTATE[HY000] [2002] Connection refused
I can connect to the same Database via Phpstorm with the same Password and Username.
It seems that this is not a problem related to the PHP Configuration.
The error Connection refused shows, from my point of view, that you can't establish a connection from the php container to the mysql container.
You need to expose the 3306 Port to the Webserver Container so that the PHP Container can establish a connection to the database. If you already bridged the containers you need to use the containers IP address and not your loopback 127.0.0.1.
Please see this answer for more information how to connect both containers and how to make a connection from a php to a mysql container:
https://stackoverflow.com/a/43128428/1118905
To narrow down the problem, you can try to establish a connection from within the PHP Container via Netcat to your given DB Host.
For example you can try to establish a connection with the following commands:
Get into the container from which you want to test the connection. docker exec -it <name_of_container> bash
Test to open up a connection via netcat (If not all ready available install it via f.e. apt) nc -vz 127.0.0.1:3306
If you are inside container, 127.0.0.1 is not known as a service that hosts the database. You can use the mysql container name instead. For example $serverName = "mysql"; depending on the name of your container.
sample service definition
services:
mysql:
image: 'mysql:5.5'
container_name: mysql
ports:
- '33066:3306'
...
Also note that the port to be used is the internal one.

How to connect Docker PHP container to MySql container?

I have created a docker container with MySQL:
docker run --name mysqlfordocker -p3307:3306 -e MYSQL_ROOT_PASSWORD=password_db-d mysql
It works as expected.
It is used by MySQLWorckbech and PHP application which are not in the container with MySQL:
//CONNECTION BY PHP APPLICATION NOT IN CONTAINER
$servername = "127.0.0.1:3307";
$username_db = "username_db";
$password_db = "password_db";
$db = "db";
The Dockerfile for my PHP application is:
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
Then I created a container with my PHP application:
docker run –d –p 5000:80 myphpapplication
The PHP application runs, but it has issues with database connection to MySQL container.
I tried to configure a connection servername in a different way but without any luck:
$servername = "127.0.0.1:3307";
$servername = "locahosto:3307";
$servername = "10.0.75.1:3307"; //DockerNAT
$servername = "172.17.0.2:3307"; //Ip by docker inspect mysql
Could you please help me on this?
Ps.
There are two parts to this, one is getting the right IP address of the container. Either the actual IP address should work- 172.17.0.2, but you should also be able to use 172.17.0.1.
Also you normally put the port number as a separate parameter...
$servername = "172.17.0.1";
$username_db = "username_db";
$password_db = "password_db";
$db = "db";
$port= = 3307;
$db = mysqli_connect($servername, $username_db, $password_db, $db, $port);

Docker Container Connecting To Host MySQL

I was following along a docker tutorial that used a container for MySQL. That worked, but I am trying to connect to my host's MySQL from a php/apache container.
I created a database called 'weather', a user 'admin'#'%' and granted the user all privileges to the weather database. I also created the necessary table/columns.
However, I keep getting the following message:
Warning: mysqli::__construct(): (HY000/2002): Connection refused in /var/www/html/index.php on line 15
Failed to connect to MySQL: Connection refused
Here's where the php app inside the container fails the connection:
<?php require 'vendor/autoload.php';
// Create a new Container
$container = new \Slim\Container([
// Add Guzzle as 'http'
'http' => function () {
return new GuzzleHttp\Client();
},
// Add mysqli as 'mysql'
'mysql' => function () {
$mysqli = new mysqli(
getenv('DATABASE_HOST'),
getenv('DATABASE_USER'),
getenv('DATABASE_PASSWORD'),
getenv('DATABASE_NAME')
);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit;
} else {
return $mysqli;
}
},
]);
I installed all the dependencies with composer and bound my host's ip address (172.17.0.1) in my.cnf. Here's the docker command I'm running:
docker run -d --rm --name=weather-app -p 38000:80 -v \
$(pwd):/var/www/html \
-e DATABASE_HOST='172.17.0.1' \
-e DATABASE_USER='admin' \
-e DATABASE_PASSWORD='password' \
-e DATABASE_NAME='weather' \
shiphp/weather-app
Here's the git repo if more info is needed: https://github.com/shiphp/weather-app.
Thanks in advance.
EDIT:
I figured out what's going on. I forgot to add the [mysqld] header in my.cnf when I bound the address. It works now.

PHP Connection to DB2

I am trying to connect a database from php script.
<?php
$database = '****';
$user = '*****';
$password = '******';
$hostname = '********';
$port = 50000;
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');
if ($conn) {
echo "Connection succeeded.";
db2_close($conn);
}
else {
echo "Connection failed.";
}
?>
I am geting the following error.
Call to undefined function db2_connect() in /home/s1.php on line 10
Can somebody Help me out how to resolve the following.
I think, you need to install DB2 extension.
Here is the link
http://php.net/manual/en/ibm-db2.installation.php
In addition to installing the db2 extension through PECL, you will need development header files and libraries downloaded on the system before running pecl install.
Here is a shell script that creates 3 files:
Dockerfile
docker-compose.yml
html/index.php
Obviously, please read script before copy/pasting to ensure you're comfortable
with what it does, but in short, it uses cat and the heredoc syntax to output
text into files:
#! /bin/sh
cat << 'EOF' > docker-compose.yml
version: '3'
services:
odb-web:
build: .
ports:
- 3030:80
volumes:
- ./html:/var/www/html
mydb2:
image: ibmcom/db2
ports:
- 50000:50000
volumes:
- ./data:/database
environment:
LICENSE: accept
DB2INST1_PASSWORD: ChangeMe!
DBNAME: testdb
privileged: true
EOF
cat << 'EOF' > Dockerfile
FROM php:7.3-apache
# To build the ibm_db2 extension, the DB2 application development header files and libraries must be installed on your system.
# DB2 does not install these by default, so you may have to return to your DB2 installer and add this option.
# The header files are included with the DB2 Application Development Client freely available for download from
# the IBM DB2 Universal Database » support site: https://www.ibm.com/developerworks/downloads/im/db2express/index.html
# https://github.com/php/pecl-database-ibm_db2
# Download linuxx64_odbc_cli.tar.gz from https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/
## add header files and libraries
RUN mkdir -p /opt/ibm/ && curl https://public.dhe.ibm.com/ibmdl/export/pub/software/data/db2/drivers/odbc_cli/linuxx64_odbc_cli.tar.gz | tar -xz -C /opt/ibm/
# if you prefer to keep the file locally, download it and use:
# ADD odbc_cli/linuxx64_odbc_cli.tar.gz /opt/ibm/
## set env vars needed for PECL install
ENV IBM_DB_HOME=/opt/ibm/clidriver
ENV LD_LIBRARY_PATH=/opt/ibm/clidriver/lib
## install ibm_db2 drivers
RUN pecl install ibm_db2
RUN echo "extension=ibm_db2.so" > /usr/local/etc/php/conf.d/ibm_db2.ini
EOF
mkdir html && cat << 'EOF' > html/index.php
<?php
$database = 'testdb';
$user = 'db2inst1';
$password = 'ChangeMe!';
$hostname = 'host.docker.internal';
$port = 50000;
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=$database;" .
"HOSTNAME=$hostname;PORT=$port;PROTOCOL=TCPIP;UID=$user;PWD=$password;";
$conn = db2_connect($conn_string, '', '');
if ($conn) {
echo "Connection succeeded.\n";
db2_close($conn);
}
else {
echo "Connection failed.\n";
}
?>
EOF
upon running this script (or if on windows, copy pasting the file contents manually), you will have 3 files, and can run docker-compose up -d to build a php 7.3 image with apache and then it brings up two containers -- the php apache server and the ibm db2 database.
Browsing to http://localhost:3030 you should see "Connection succeeded".
You can modify the html/index.php file as desired and refresh the page to test things out.
just download a suitable version from PECL

Categories