Can’t Connect to MySQL Server on ‘db’ (115) Error in Docker
Hello! I recently faced this issue while trying to set up an existing Magento project using the Docker Compose template. The error message “ERROR 2002 (HY000): Can’t connect to MySQL server on ‘db’ (115)” was quite puzzling, especially since I could successfully connect to the same MySQL service outside the Docker container.
The Problem
Here’s a summary of my steps and the issue:
- Installed Docker & Docker Compose on Ubuntu 18.04.
- Downloaded the Docker Compose template:
curl -s https://raw.githubusercontent.com/markshust/docker-magento/master/lib/template | bash - Replaced
srcwith my existing Magento instance files:cp -R ~/Sites/existing src - Ran
docker-compose up -d. - Copied files to the container using
bin/copytocontainer --all. - Imported the existing database using
bin/mysql < /var/www/magento243.sql.
However, when I tried to import the database, I got the error:
ERROR 2002 (HY000): Can't connect to MySQL server on 'db' (115)
Even trying telnet db 3306 resulted in a “Connection timed out” response.
The Solution
After some troubleshooting, I realized the issue was with the network configuration inside the Docker containers. Here are the steps that resolved the problem:
1. Check the docker-compose.yml file
Ensure that the db service is defined correctly in your docker-compose.yml file. In my case, I had to update the extra_hosts section for the db container to include the correct hostnames and IP addresses.
services:
# ... other services ...
db:
image: mariadb:10.4
command: --max_allowed_packet=256M
ports:
- "3306:3306"
env_file: env/db.env
volumes:
- dbdata:/var/lib/mysql
extra_hosts:
## M1 Mac support to fix Docker delay, see #566
- "app:172.17.0.1"
- "phpfpm:172.17.0.1"
- "db:172.17.0.1" # Update this line to match your network configuration
- "redis:172.17.0.1"
- "elasticsearch:172.17.0.1"
- "rabbitmq:172.17.0.1"
2. Update the MySQL configuration file
If the issue persists, you may need to update the MySQL configuration file located at db/etc/mysql/conf.d/mysqld.cnf. Change the bind-address setting from 0.0.0.0 to db, like this:
nano db/etc/mysql/conf.d/mysqld.cnf
Then, update the bind-address:
bind-address = db
Save and exit (press Ctrl+X, then press Enter).
3. Restart the Docker containers
Finally, restart your Docker containers using the following command:
docker-compose up -d
Conclusion
In my experience, network configuration issues are often the root cause of “Can’t connect to MySQL server” errors in Docker environments. Always ensure that you have correctly configured the extra_hosts for each container and updated any relevant configuration files.
Remember to replace any placeholders with your actual values if needed. If you’re still having trouble, feel free to consult Laravel Company’s resources for more in-depth guides on Magento development and Docker setup.