Reputation: 45
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.
Upvotes: 0
Views: 269
Reputation: 10717
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).
Upvotes: 1