Docker Container Connecting To Host MySQL - php

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.

Related

PHP to DB2 with PDO_IBM Error : SQLDriverConnect: -1390 [IBM] [CLIDRIVER] SQL10007N

In Ubuntu 22.04 I am attempting to connect PHP with a DB2 database via the driver pdo_ibm.so
I have followed this guide, along with IBM documentation: https://github.com/php/pecl-database-pdo_ibm
I've compiled version 1.5.0. into the ".so" file and placed it on the respective driver's folder.
However I am getting the following error
SQLDriverConnect: -1390 [IBM] [CLIDRIVER] SQL10007N Message "0" could not be retrieved. Reason code "3".
Using the following PHP code:
var_dump($dsn);
echo "". PHP_EOL;
var_dump($this->_config['username']);
var_dump($this->_config['password']);
var_dump($this->_config['driver_options']);
$this->_connection = new PDO(
$dsn,
$this->_config['username'],
$this->_config['password'],
$this->_config['driver_options']
);
/*$this->_connection = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
"HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP;", "db2inst1", "123456", array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
); */
I am using the follwing env variables, set on the ~/.bashrc file:
ODBCHOME=/home/poc-dev/etc
ODBCINI=/home/poc-dev/clidriver/system_odbc.ini
DB2INSTANCE=db2inst1
DB2HOME=/home/poc-dev/clidriver
IBM_DB_HOME=/home/poc-dev/clidriver
LD_LIBRARY_PATH=/home/poc-dev/clidriver/lib
_=/usr/bin/printenv
I have succesfully connected with DBeaver and ISql to the database
What am I missing?
Edit: The user running PHP is "www-data" image of apache envvars:
Apache2 uses the "www-data" user to run PHP. As that "www-data" has to have full access to the DB2 CLIDRIVER in all senses as user mao pointed out.
I have found that I had to place the exact same variables as ~/.bashrc in the etc/enviroment file (I was mistakenly thinking I made them global), after I did that I could see the enviroment variables as the "www-data" user which I verified via the command:
sudo -u www-data printenv
I confirmed the ENV-variables for the DB2 CLIDRIVER files folder: /home/poc-dev/clidriver were there, but they had 755 permissions which I needed to change to 777 permission via the command:
sudo chmod 777 -R /home/poc-dev/
After that I tested the ISQL command on the user "www-data" by the command (since the first time I realized I was getting a message where ISQL could not find one of the libraries, which turned out to be a permissions problem):
sudo -u www-data isql TEST db2inst1 123456
"TEST" being the registered DSN in odbc.ini, "db2inst1" being the user on the dataserver (in a virtual machine in this case)
Then I proceded to use:
$this->_connection = new PDO("ibm:DRIVER={IBM DB2 ODBC DRIVER};DATABASE=testdb;" .
"HOSTNAME=localhost;PORT=50000;PROTOCOL=TCPIP;", "db2inst1", "123456", array(
PDO::ATTR_PERSISTENT => FALSE,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
In PHP. Hopefully this helps someone

"Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused" after updating a PHP file [duplicate]

I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the "mysql"
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
I spent quite a few hours in a docker environment where all my containers are docker containers and I was using Phinx for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx in following way.
docker compose --env-file .env run --rm phinx status -e development
Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"
Solved this by putting 'port' => '8889', in 'Datasources' => [
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT to false in the new PDO options array, besides the entry PDO::MYSQL_ATTR_SSL_CA for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I've also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC, Type :wq, and hit Enter
In Terminal run source ~/.bash_profile
In Terminal type which php, output should be the path to MAMP PHP install.
I had the same issue on a docker container from php:8.0-fpm-alpine image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'#'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.

Docker php8.1 cant connect to MySQL [duplicate]

I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the "mysql"
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
I spent quite a few hours in a docker environment where all my containers are docker containers and I was using Phinx for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx in following way.
docker compose --env-file .env run --rm phinx status -e development
Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"
Solved this by putting 'port' => '8889', in 'Datasources' => [
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT to false in the new PDO options array, besides the entry PDO::MYSQL_ATTR_SSL_CA for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I've also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC, Type :wq, and hit Enter
In Terminal run source ~/.bash_profile
In Terminal type which php, output should be the path to MAMP PHP install.
I had the same issue on a docker container from php:8.0-fpm-alpine image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'#'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.

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

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

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.

Categories