Can't connect to between mysql container and php in docker - php

Trying to connect to mysql 8 (mysql:latest) from a php:latest image (without apache or nginx) and I'm getting this annoying error:
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] Connection refused in /src/conn.php:5
Stack trace:
#0 /src/conn.php(5): PDO->__construct('mysql:host=data...', 'root', '12345678')
#1 {main}
thrown in /src/conn.php on line 5
I've looked for +20 solutions here on stackoverflow but none of them was able fix my problem. I can connect without a problem using mysql workbench or DataGrid using the following credentials:
server: localhost user: root pass: 12345678
But any configuration I use on the php image I can't make them connect with each other.
My docker-compose file:
version: '3'
services:
composer:
container_name: composer
networks:
- backend
image: composer
volumes:
- .:/app
command: install
database:
container_name: mysql
networks:
- backend
image: mysql:latest
volumes:
- ./database/mysqldata:/var/lib/mysql
command: --default-authentication-plugin=mysql_native_password
environment:
MYSQL_ROOT_PASSWORD: 12345678
MYSQL_DATABASE: testdb
ports:
- "3306:3306"
php:
build:
context: .
container_name: php
networks:
- backend
image: php:apache
links:
- database
env_file:
- .env
volumes:
- .:/
command:
php /src/conn.php
depends_on:
- composer
- database
networks:
backend:
My conn.php:
<?php
$db = new PDO('mysql:host=database;dbname=testdb', 'root', '12345678');
What I did until now to try to fix the problem:
Change conn.php host to 127.0.0.1
Change conn.php host to localhost
Tried to use mysqli (got also connection refused)
Tried another php images (with apache, nginx etc)
Tried to use mysql as a host
PS: I'm using docker for mac
After 5 hours of research I really don't know what else to do and as I'm not a docker expert, would appreciate any help to point me the direction of the fix.
Thank you!

In your case, you can't connect to mysql via localhost or 127.0.0.1. If you connect like this. It call to localhost inside php container. But there is no mysql install in your php container.
You must connetc via container name. Or docker inspect you mysql container and get the container IP. For example with your docker-compose
database:
container_name: mysql
Now your mysql database host is mysql - container name instead localhost

Was able to find the solution. Turns out I need to wait for mysql service to be available before I start the php script. So I used the wait-for-it solution and did this on docker-compose:
command: >
bash -c "chmod +x /docker/./wait-for-it.sh
&& /docker/./wait-for-it.sh database:3306 -- echo 'database is up'
&& php phpscript.php"
Thank you for the help

Related

Mysql - Docker: Connection issue

My docker-compose.yml looks like this:
version: '3.3'
services:
frontend:
build: frontend
container_name: yii-frontend
ports:
- 20080:80
volumes:
# Re-use local composer cache via host-volume
- ~/.composer-docker/cache:/root/.composer/cache:delegated
# Mount source-code for development
- ./:/app
networks:
- my-marian-net
backend:
build: backend
container_name: yii-backend
ports:
- 21080:80
volumes:
# Re-use local composer cache via host-volume
- ~/.composer-docker/cache:/root/.composer/cache:delegated
# Mount source-code for development
- ./:/app
networks:
- my-marian-net
db:
image: mysql:8.0
container_name: mysql8
command: --user=root --default-authentication-plugin=mysql_native_password
restart: always
environment:
- MYSQL_ROOT_PASSWORD=verysecret
- MYSQL_DATABASE=yii2advanced
- MYSQL_USER=yii2advanced
- MYSQL_PASSWORD=secret
ports:
- 6033:3306
networks:
- my-marian-net
networks:
my-marian-net:
driver: bridge
I get an error message:
'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed:
nodename nor servname provided, or not known'
Solutions I have tried:
Ping from backend and frontend container to mysql8: docker exec -ti yii-frontend ping mysql8 (It works!)
Manually connect each container to the same network (my-marian-net) docker network connect my-marian-net mysql8 (same for each container)
I have connected into the mysql container and test connection there, it works.
I have connected from containers to mysql8 container MySQL service and it works.
So far no luck getting connected. In my code, I am using "db" as hostname since I am using bridge mode.
After trying different solutions, I have isolated the issue to a connection from
outside docker, Any suggestion?
I am using macOS Mojave. Docker version 19.03
The issue was simpler than I thought, from outside container "db" service does not exist, so no possibility to get connected.
In the future when I run console commands from local, I will change host in database connection to use localhost instead of "db" or get connected to the container itself and run them from inside.
Thanks to #Smankusors for the help.

Symfony 4 "Connection refused" while trying to connect to docker mysql container

My question is how to configure connection to mysql container.
Here is my docker-compose.yml
version: '3'
services:
php:
build: ./php-fpm
volumes:
- ./iym:/var/www/iym
- ./php-fpm/php.ini:/usr/local/etc/php/php.ini
depends_on:
- mysql
web:
build: ./nginx
ports:
- "8888:80"
volumes:
- ./iym:/var/www/iym
- ./nginx/iym.conf:/etc/nginx/conf.d/default.conf
depends_on:
- php
mysql:
image: mysql:5.6
restart: always
command: --default-authentication-plugin=mysql_native_password
volumes:
- ${DB_PATH_HOST}:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: "symf0ny"
ports:
- "3306:3306"
And here is my DATABASE_URL in .env file
DATABASE_URL=mysql://root:symf0ny#127.0.0.1:3306/iym
When i try to run php bin/console doctrine:database:create i get an error like "SQLSTATE[HY000] [2002] Connection refused". OS - ubuntu 18.04. What should i do to connect to DB? Many thanks!
I assume you are trying to connect from another container/service defined in docker-compose and you are using current version of docker-compose (2.4 or 3.7)
You need to change
DATABASE_URL=mysql://root:symf0ny#127.0.0.1:3306/iym
to
DATABASE_URL=mysql://root:symf0ny#mysql:3306/iym
The reason is that 127.0.0.1 is refering to the localhost of the machine on which php runs. In this case it's the php's container localhost. But the db doesn't run there. It runs in another docker container, which can be reached under the service name, mysql in this case.
In docker-compose networking docs is written:
By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.
but, the service is discoverable under the container name (which is automatically generated to projectName_serviceName_1 (project name begin by default folder name), but also under service name, link and service alias if defined. I would recommend using service name wherever possible.
More in docs: https://docs.docker.com/compose/networking/
In my case, the Docker variable overrides the parameter from .env file and I'm trying to connect to the wrong host. Found that via dd($this->constructPdoDsn($params)) in the Doctrine\DBAL\Driver\PDO\MySQL\Driver::connect, maybe it will be helpful

Symfony + Docker, connection refused

I'm seasoned in Symfony but quite new to docker, and I have a "connection refused error" I don't manage to solve.
Pretty sure it is a beginner error and that the solution here is quite simple...
Here is the content of my docker-compose file:
version: '3.2'
services:
cg-demo:
build: docker/cg-demo
container_name: cg-demo
working_dir: /var/www/html
volumes:
- .:/var/www/html
- ./docker/demo/vhost.conf:/etc/apache2/sites-available/000-default.conf:ro
- ./docker/demo/php.ini:/usr/local/etc/php/php.ini:ro
- ~/.ssh:/var/www/.ssh
- ~/.composer:/var/www/.composer
environment:
- SYMFONY_ENV
- DOMAIN_NAME: cg-demo.docker
- VIRTUAL_HOST: cg-demo.docker
depends_on:
- database
env_file: .env
ports:
- 8000:80
database:
image: percona:5.6
ports:
- 3306:3306
expose:
- 3306
container_name: cg-demo-database
volumes:
- /docker/database:/etc/mysql/conf.d
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: demo
tmpfs:
- /var/lib/mysql
- /tmpfs:size=300M
This has been based from another project that works, but I'm not sure of all that's happening here...
I also have a phpmyadmin container, not shown here. PhpMyAdmin connects correctly to the database and can use it without problem from any web server. However when it comes to the symfony container, I have this whenever trying to use the database:
[Doctrine\DBAL\Exception\ConnectionException]
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
[Doctrine\DBAL\Driver\PDOException]
SQLSTATE[HY000] [2002] Connection refused
[PDOException]
SQLSTATE[HY000] [2002] Connection refused
The connection information is the following, in a .env file:
# Database credentials
DATABASE_HOST=database
DATABASE_PORT=3306
DATABASE_USER=root
DATABASE_PASSWORD=root
DATABASE_DB=cg-demo
Calling docker ps gives me this:
CONTAINER ID IMAGE COMMAND
CREATED STATUS PORTS NAMES
16a67dadeebb phpmyadmin/phpmyadmin "/run.sh phpmyadmin" 15 minutes ago Up 15 minutes 0.0.0.0:8001->80/tcp cg.phpmyadmin.docker
8bd783aa1dd1 cg_cg-demo "entrypoint.sh apa..." 15 minutes ago Up 15 minutes 0.0.0.0:8000->80/tcp cg-demo
2fc7cd9105ba percona:5.6 "docker-entrypoint..." 15 minutes ago Up 15 minutes (healthy) 3306/tcp cg-database
I've tried to ping database from the demo container and it works...
EDIT 1:
Added the following to the database container:
ports:
- 3306:3306
EDIT 2:
Removed the following from all containers:
networks:
- default
EDIT 3:
My doctrine configuration in app/config/config.yml:
dbal:
host: "%env(DATABASE_HOST)%"
port: "%env(DATABASE_PORT)%"
dbname: "%env(DATABASE_DB)%"
user: "%env(DATABASE_USER)%"
password: "%env(DATABASE_PASSWORD)%"
charset: UTF8
mapping_types:
enum: string
server_version: 5.6
EDIT 4:
Added the following to the database configuration:
expose:
- 3306
This answer is for docker-compose version 2 and it also works on version 3:
The problem is a Linking Containers problem. We need to define additional aliases that services can use to reach one another.
Expose 3306 port will not solve your problem. mysql or percona container will expose by deffault that port. Take a look to the docker hub of percona image.
. It's mentioned there:
Connect to MySQL from an application in another Docker container
This image exposes the standard MySQL port (3306), so container
linking makes the MySQL instance available to other application
containers. Start your application container like this in order to
link it to the MySQL container:
$ docker run --name some-app --link some-percona:mysql -d application-that-uses-mysql
So, you should links the database to you cg-demo container. There's tow solutions:
1) Add a link under configuration :
services:
cg-demo:
build: docker/cg-demo
container_name: cg-demo
.
.
.
links:
- mysql
The diffirence between depeds_on and links is that depends_on docker-compose up will start services in dependency order. In your following example, database will be started before web.
We can also access data. But this is not enough, because we want to make sure that your web container (cg-demo) always connect to the database container.
Links allow you to define extra aliases by which a service is reachable from another service.
In the following example, database is reachable from web (cg-demo) at the hostname database. This means that thecg-demo can connect the database contanier from the 3306 port.
2) The second solution, is to configure the default network instead of (or in addition to) customizing your own network. Simply define a default entry under networks:
networks:
bridge_name:
driver: bridge
And then you should link every container to that bridge via networks tag:
cg-demo:
.
.
networks:
- bridge_name
database:
.
.
networks:
- bridge_name

Console PHP script runs differently when executes through docker exec or through PhpStorm

I'm trying to run console run Doctrine 2's console script through the PhpStorm. Docker is set up as Deploy server.
If I run this:
$ docker exec container_name /var/www/vendor/bin/doctrine-module orm:schema-tool:create
it prints:
No Metadata Classes to process.
But when I run PHP Run/Debug configuration in PhpStorm:
File: /home/username/PhpstormProjects/proj/vendor/bin/doctrine-module
it prints:
docker://image_name/container_name /var/www/vendor/bin/doctrine-module
Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/vendor/zendframework/zend-servicemanager/src/ServiceManager.php on line 765
Zend\ServiceManager\Exception\ServiceNotCreatedException: Service with name "doctrine.connection.orm_default" could not be created. Reason: An exception occured in driver: SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known in /var/www/vendor/zendframework/zend-servicemanager/src/ServiceManager.php on line 765
Call Stack:
0.0001 349368 1. {main}() /var/www/vendor/doctrine/doctrine-module/bin/doctrine-module:0
0.0268 360480 2. include('/var/www/vendor/doctrine/doctrine-module/bin/doctrine-module.php') /var/www/vendor/doctrine/doctrine-module/bin/doctrine-module:4
0.9376 4076096 3. Zend\ServiceManager\ServiceManager->get() /var/www/vendor/doctrine/doctrine-module/bin/doctrine-module.php:61
0.9376 4076096 4. Zend\ServiceManager\ServiceManager->doCreate() /var/www/vendor/zendframework/zend-servicemanager/src/ServiceManager.php:200
Process finished with exit code 255
I checked that when PDO is creating it receives absolutely the same arguments
new PDO("mysql:host=db;port=3306;dbname=dbname", "user", "pass", [])
docker-compose.yml:
version: '2'
services:
nginx:
container_name: nginx
build:
context: .
dockerfile: DockerfileNginx
ports:
- "80:80"
depends_on:
- php
working_dir: /var/www
links:
- php
volumes:
- .:/var/www
links:
- db
php:
container_name: php
build:
context: .
dockerfile: DockerfilePhp
- db
volumes:
- .:/var/www
expose:
- "9000"
depends_on:
- db
db:
container_name: db
image: "mysql:5.6"
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: pass
MYSQL_DATABASE: dbname
MYSQL_USER: user
MYSQL_PASSWORD: pass
I had the same problem and I found out, that PHPStorm starts a new, dedicated Docker container for your PHP calls. So, all your docker-compose configuration is missing at this point.
I did the following:
start your Docker stack with compose
after that find your network name with docker network ls (see Cannot link to a running container started by docker-compose for help)
inside PHPStorm goto your preferences for your Docker container (Languages & Frameworks -> PHP -> PHPUnit: Docker container ...) and add a link to your db (something like: name = your_containter_name_1, alias = db) and change the network mode from bridge to your network name

Docker MYSQL '[2002] Connection refused'

I was trying out Docker for the first time. Got a LEMP stack up and running, but I can't connect to the MYSQL Database. Not on my Symfony application, not on PHPMyAdmin. The applications are returning the following error code:
An exception occured in driver: SQLSTATE[HY000] [2002] Connection refused
This is my docker-compose.yml:
nginx:
image: tutum/nginx
ports:
- "80:80"
links:
- phpfpm
volumes:
- ./nginx/default:/etc/nginx/sites-available/default
- ./nginx/default:/etc/nginx/sites-enabled/default
- ./logs/nginx-error.log:/var/log/nginx/error.log
- ./logs/nginx-access.log:/var/log/nginx/access.log
phpfpm:
build: phpfpm/
ports:
- "9000:9000"
volumes:
- ./public:/usr/share/nginx/html
mysql:
image: mariadb
ports:
- 3306:3306
environment:
MYSQL_ROOT_PASSWORD: admin
phpmyadmin:
image: phpmyadmin/phpmyadmin
restart: always
links:
- mysql
ports:
- 8183:80
environment:
MYSQL_USERNAME: admin
MYSQL_ROOT_PASSWORD: admin
PMA_ARBITRARY: 1
Dockerfile PHPFPM:
FROM php:fpm
RUN docker-php-ext-enable opcache
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpq-dev \
&& docker-php-ext-install mysqli pdo_pgsql pdo_mysql
GitHub URL: https://github.com/MolengraafFrank/DockerSymfony
Could someone help me out? Thank you for your time.
The '[2002] Connection refused' means you can reach the database server, but you don't have right access for the user (in your case admin). By default mariadb have a root user with the password given by MYSQL_ROOT_PASSWORD and this user can connect from any server (%).
If you want use an over login to your databases, you have to create it in the databases server with the right granting on databases from chosen locations.
The problem here is that you have named your database server as 'mysql' (service name in the docker-compose file). But by default phpmyadmin tries to connect to a database server named 'db'. Adding PMA_HOST: mysql under the environment section of the phpmyadmin service will resolve this problem.
I think that MYSQL_USERNAME and PMA_ARBITRARY are useless if you work with default configuration (connection with root to your databases server)
I had this challenge because I am running 3 different containers with different IP Addresses
db - 172.18.0.3 - container for MYSQL
app - 172.18.0.2 - container for Laravel app
so I fixed it by editing my Laravel .env file
DB_CONNECTION=mysql
DB_HOST=172.18.0.3
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
...
To get your containers Ip addresses. From your docker host
docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)
UPDATED:
For latest docker versions and based on the services name, "mysql", in your docker-compose.yml
mysql:
image: mariadb
ports:
- 3306:3306
You can try this:
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=username
DB_HOST is the name of MySQL service name defined in docker-compose.yml
I've managed to connect to the mysql instance using mysql command line tool, this is the command I used - mysql -u root -p -h 127.0.0.1, and the entering the admin password. Is that a sufficient solution for you?
In my case I was running mysql in a docker container whose port was mapped to the host mac (3306:3306). I tried connecting to this database from a phpmyadmin docker container using 127.0.0.1 . But it won't work because the localhost on the phpmyadmin docker container does not have the required mysql running.
To connect to the host from docker network
docker.for.mac.host.internal
Docker Networking Docker Compose Networking
For my instance, the issue was with port mapping somehow.
In my case it was 3307:3306, as soon as I changed it to 3307 on the right side as well, I could connect to the DB instance.
Adding DB_READ_HOST=db solved this problem for me
If you want to know why your connexion failed, you can use in your terminal php artisan tinker and then
like
DB::connection()->getPdo();
Unfortunately this will only give you a part of the error.
Quit tinker and then use this command php artisan db will give you more information like database type, host, port, ad user about the issue.
Like this one
ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (61)
Symfony\Component\Process\Exception\ProcessFailedException
The command "'mysql' '--host=127.0.0.1' '--port=3306' '--user=root' '--default-character-set=utf8mb4' 'laravel'" failed.
Exit Code: 1(General error)
Working directory: /Users/Dev/Documents/www/laravel_docker/src/addressAPI
Output:
================
Error Output:
================
at vendor/symfony/process/Process.php:270
266▕ */
267▕ public function mustRun(callable $callback = null, array $env = []): self
268▕ {
269▕ if (0 !== $this->run($callback, $env)) {
➜ 270▕ throw new ProcessFailedException($this);
271▕ }
272▕
273▕ return $this;
274▕ }
+14 vendor frames
15 artisan:37
Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput))
This will not give you the answer on what is wrong, but at least you can understand why your config is wrong.
you need to link the phpfpm container to mysql.

Categories