E
E
Elena2019-11-13 12:28:02
PHP
Elena, 2019-11-13 12:28:02

How to connect a local database in php in docker?

The docker-compose.yml file looks like

version: '3'

services:
  nginx:
    image: nginx:latest
    ports:
      - 9080:80
    volumes:
      - ./docker/nginx/default.conf:/etc/nginx/conf.d/default.conf
      - ./:/var/www/html
      - ./logs:/var/log/nginx
    depends_on:
      - php
  php:
    build:
      context: ./docker/php
    ports:
      - 9000:9000
    volumes:
      - ./:/var/www/html
      - ./logs:/var/log/
      - ./docker/php/php.ini:/usr/local/etc/php/php.ini
    restart: always
    extra_hosts:
      - host.docker.internal:$DOCKER_HOST_IP

The site is launching. But you still need a connection to the database, which is already deployed locally. I tried adding network_mode: "host" to the images. But my domain stops working in the browser.
Connection to the database through the console received:
docker run --rm -it --network=host mysql php -h 127.0.0.1 -uroot -p

Now I'm thinking how to fasten it to my images.
The code I'm trying
//$link = mysqli_connect('172.17.0.1', 'root', '1234qwer');
$link = mysqli_connect('127.0.0.1', 'root', '1234qwer');

if (!$link) {
    echo "Ошибка: Невозможно установить соединение с MySQL." . PHP_EOL;
    echo "Код ошибки errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Текст ошибки error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}

In Mysql config I wrote
bind-address = 127.0.0.1

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2019-11-13
@q2digger

You must connect from the container not to the localhost (127.0.0.1), but to the external address of your docker host (for example, let's say 192.168.1.1)
Accordingly, there must be a user in mysql with the appropriate access permissions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question