I have web-app with PHP and database in docker-compose file:
version: '2'
networks:
default:
driver: bridge
services:
yii2-app:
build:
context: ./web
ports:
- "80:80"
networks:
- default
depends_on:
- yii2-db
- queue
environment:
DB_NAME: ${WEB_DB_NAME}
DB_USERNAME: ${WEB_DB_USERNAME}
DB_PASSWORD: ${WEB_DB_PASSWORD}
yii2-db:
image: mysql:5.7.16
command: --default-authentication-plugin=mysql_native_password
networks:
- default
expose:
- "3306"
environment:
MYSQL_ROOT_PASSWORD: ${WEB_DB_PASSWORD}
MYSQL_DATABASE: ${WEB_DB_NAME}
volumes:
- "./web/db:/var/lib/mysql"
...
When I start services via docker-compose up
my PHP-app makes db migrations. But this error occured in database connection:
Exception 'yii\db\Exception' with message 'SQLSTATE[HY000] [1045] Access denied for user 'root'@'172.21.0.8' (using password: YES)'
It's strange, because in my PHP-app I use name of db service yii2-db
and docker by itself to define the correct IP.
I connect to my PHP-app container via
docker exec -it passportrecognition_yii2-app_1 bash
and check mysql connection via mysql-client
mysql -h yii2-db -u root -p
ERROR 1045 (28000): Access denied for user 'root'@'172.21.0.8' (using password: YES)
But 172.21.0.8
is not the IP of my db, it's the IP of my PHP-app. That is PHP-app make db-connect to itself.
Database IP is 172.21.0.4
as shown with this ping
command:
ping yii2-db
PING yii2-db (172.21.0.4): 56 data bytes
64 bytes from 172.21.0.4: seq=0 ttl=64 time=0.145 ms
And another strange moment: when I connect directly on database IP 172.21.0.4
, the following error occurs:
bash-4.4# mysql -h 172.21.0.4 -u root -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'172.21.0.8' (using password: YES)
Why can't I connect to my database? Why does Docker define an invalid IP for the db service?