[Solved] SQLSTATE[HY000] [2002] Connection refused to report an error when PHP connects to mysql in the docker container

Laradock is a complete PHP local development environment provided by Docker

Error when connecting to MySQL in the framework

SQLSTATE[HY000] [2002] Connection refused

The main reason is that there is not enough understanding of the isolation mechanism of Docker containers. Each container is isolated. If there are interdependent services, it is necessary to perform display associations, such as using options --link.
In the same way, docker-composewhen using , the association between containers is similar to the following method:

# docker-compose.xml basic
version: '2'
services:
	
	...
	
    php:
        build: ./php
        
        ...
        
        links:
            - "mysql"
           
    mysql:
        build: ./mysql
        ports:
            - "3306:3306"
        environment:
            MYSQL_PASSWORD: root

Note that the key point is here: the code to test the connection to MySQL is actually running in the container corresponding to PHP, and the MySQL service is in its own container. When our host fills in 127.0.0.1, it actually corresponds to the PHP container. Inside, so it is impossible to find the corresponding service, which causes the above connection refused error.

So, how do you connect?

In fact, after the containers are associated, they can be connected by the container name.

In the above docker-compose.xmldocument, the container corresponds to the service name MySQL mysql, PHP container name is associated with it mysql, so the 127.0.0.1change mysqland then connect to.

# thinkphp project modify database.php file
'hostname'        => 'mysql',

# Laravel project modify .env file
DB_HOST=mysql


Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *