Laradock SQLSTATE[HY000] [2002] Connection timed out

Somtimes tinkering with Laradock containers you may get a SQLSTATE[HY000] [2002] Connection timed out or to be more specifically

Illuminate\Database\QueryExceptionPOST /login
SQLSTATE[HY000] [2002] Connection timed out (SQL: select * from `users` where `email` = jasper@domain.test limit 1)

This could be because post rebuilding or loading the container got a new ip address. To check the ip addresses of all containers you can do a

docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)

to check them. Then you can change the ip address for the database containers accordingly. In our case we had

DB_HOST=192.168.32.7
DB_DATABASE=database
DB_USERNAME=default
DB_PASSWORD=secret
DB_PORT=3306

You can also use mariadb as the host as we mentioned it the Laradock Setup Snags Post. But only when one container is generated. Read further for when you are using two of them.

Two MariaDB Containers

Using mariadb as host might often work. However, when you are using two containers like me you will need the ip or specific host for the second one:

DB_PUBLISH_HOST=172.22.0.2
DB_PUBLISH_DATABASE=project_publish_db
DB_PUBLISH_USERNAME=default
DB_PUBLISH_PASSWORD=secret
DB_PUBLISH_PORT=3306

The example showed the ip I located. You can either use that or the specific host you will find with command mentioned earlier. We had:

....
/laradock_mariadb_1 - 172.22.0.5
/laradock_redis_1 - 172.22.0.4
/laradock_mariadb_published_1 - 172.22.0.2
............

earlier. So we picked mariadb_published. So remove laradock_ and _1. As you can see there are two different host names for the two mariadb containers here. If you do not use the specific ip address or specific host name for the second database container you will keep on getting annoying connection refused issues like:

Illuminate\Database\QueryException ·POST /slug/create-something
SQLSTATE[HY000] [2002] Connection refused (SQL: select count(*) as aggregate from `projects` where `slug` = something

And of course would host be better than ip as host should stick around longer. IP addresses change.

Tagged in : Tagged in : ,
Jasper Frumau

Jasper has been working with web frameworks and applications such as Laravel, Magento and his favorite CMS WordPress including Roots Trellis and Sage for more than a decade. He helps customers with web design and online marketing. Services provided are web design, ecommerce, SEO, content marketing. When Jasper is not coding, marketing a website, reading about the web or dreaming the internet of things he plays with his son, travels or run a few blocks.