A
A
Alexander Alexandrovich2019-10-21 21:42:04
PHP
Alexander Alexandrovich, 2019-10-21 21:42:04

How to connect to a database using Docker?

Wrote a `docker-compose` file with the following content:

version: '2'

services:
  php:
    image: chialab/php:7.3-fpm
    container_name: exchange-php
    working_dir: /app
    volumes:
      - .:/app
    environment:
      - APP_ENV=test

  mysql:
    image: mysql:5.7
    container_name: exchange-mysql
    volumes:
      - './docker/mysql/my.cnf:/etc/mysql/my.cnf'
    ports:
      - 33060:3306
    environment:
      - MYSQL_ROOT_PASSWORD=root
      - MYSQL_DATABASE=test_db
      - MYSQL_USER=test_user
      - MYSQL_PASSWORD=test_password

I want to connect to the database:
docker exec exchange-php php -r "new PDO('mysql:host=exchange-mysql;port=33060;charset=utf8', 'test_user', 'test_password');"

I get an error: `SQLSTATE[HY000] [2002] Connection refused`
I go into the mysql container and check if mysql is listening on all IPs:
$ docker exec -it exchange-mysql bash
$ mysqld --verbose --help | grep bind-address

  --bind-address=name IP address to bind to.
bind-address                                                 0.0.0.0

I also checked that the user is allowed to authorize:
mysql> SELECT host, user FROM mysql.user;
+-----------+---------------+
| host      | user          |
+-----------+---------------+
| %         | root          |
| %         | test_user     |
| localhost | mysql.session |
| localhost | mysql.sys     |
| localhost | root          |
+-----------+---------------+
5 rows in set (0.00 sec)

What needs to be done to connect to mysql using php and docker?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question