[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'
        build: ./php
            - "mysql"
        build: ./mysql
            - "3306:3306"
            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, 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 mysqland then connect to.

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

# Laravel project modify .env file

Read More:

Leave a Reply

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