1

I have created a database with the following docker-compose file:

    version: '3.8'
services:
    php-apache-environment:
        container_name: php-apache
        build:
            context: ./php
            dockerfile: Dockerfile
        depends_on:
            - db
        volumes:
            - ./php/src:/var/www/html/
        ports:
            - 8000:80
    phpmyadmin:
        image: phpmyadmin/phpmyadmin
        ports:
            - '8080:80'
        restart: always
        environment:
            PMA_HOST: db
        depends_on:
            - db
    db:
        container_name: db
        image: mysql
        restart: always
        environment:
            MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD
            MYSQL_DATABASE: MYSQL_DATABASE
            MYSQL_USER: MYSQL_USER
            MYSQL_PASSWORD: MYSQL_PASSWORD
        ports:
            - "9906:3306"

I am trying to connect to it from another container running a test for connection as shown below:

    $conn = new mysqli(192.168.208.2, 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE', 9906);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} else {
    echo "Connected to MySQL server successfully!";
}

I have accessed the IP address of the container that is running the database using docker inspect (container id) for the container running 'db' at port 9906:3306. However I constantly get the following error when trying a variety of ports:

Warning: mysqli::__construct(): (HY000/2002): Connection timed out in /var/www/html/index.php on line 12

Am i doing something fundamentally incorrect? Any help would be much appreciated.

1
  • theres a missing environment variable, on phpmyadmin: environment: add another MYSQL_ROOT_PASSWORD: MYSQL_ROOT_PASSWORD Commented Aug 27, 2022 at 22:45

1 Answer 1

1

The solution is to replace 192.168.208.2 with db in your PHP code.

The explanation: each container is like a small closed box and docker compose creates a small "world" in which these boxes know each other by name (the service name) and can connect to each others' ports. The containers have no idea what is outside their world (your computer host). All they see around them is the other small boxes. It helps to imagine you are one of those boxes in order to get the concepts of isolation right.

For this reason you can also delete this:

ports:
            - "9906:3306"

this is the "portal" from the container's world to the outside. So it is only useful if you want to connect from the host to the database (with a MySQL Workbench client for example).

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.