2002 php network_error ai_generated true

PDOException: SQLSTATE[HY000] [2002] Connection timed out in /var/www/app/src/Database/Connection.php:48

ID: php/pdo-query-timeout

Also available as: JSON · Markdown · 中文
85%Fix Rate
88%Confidence
1Evidence
2023-11-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
PHP 7.4 active
PHP 8.0 active
PHP 8.1 active
PHP 8.2 active
MySQL 5.7 active
MySQL 8.0 active
MariaDB 10.5 active

Root Cause

The PDO connection to MySQL fails due to a network timeout, typically because the database server is unreachable, the firewall blocks the port, or the connection pool is exhausted.

generic

中文

PDO到MySQL的连接因网络超时而失败,通常是因为数据库服务器不可达、防火墙阻止了端口或连接池耗尽。

Official Documentation

https://www.php.net/manual/en/ref.pdo-mysql.connection.php

Workarounds

  1. 90% success Verify network reachability using `telnet db-host 3306` from the PHP server. If it fails, check firewall rules (e.g., `sudo ufw status`) and ensure the MySQL port is open. Also check MySQL's `bind-address` in `/etc/mysql/my.cnf` is set to `0.0.0.0` if remote connections are needed.
    Verify network reachability using `telnet db-host 3306` from the PHP server. If it fails, check firewall rules (e.g., `sudo ufw status`) and ensure the MySQL port is open. Also check MySQL's `bind-address` in `/etc/mysql/my.cnf` is set to `0.0.0.0` if remote connections are needed.
  2. 75% success Increase MySQL connection timeout temporarily: run `SET GLOBAL connect_timeout=60;` and `SET GLOBAL wait_timeout=600;` in MySQL, then update php.ini with `pdo_mysql.default_socket=` and restart PHP-FPM.
    Increase MySQL connection timeout temporarily: run `SET GLOBAL connect_timeout=60;` and `SET GLOBAL wait_timeout=600;` in MySQL, then update php.ini with `pdo_mysql.default_socket=` and restart PHP-FPM.

中文步骤

  1. Verify network reachability using `telnet db-host 3306` from the PHP server. If it fails, check firewall rules (e.g., `sudo ufw status`) and ensure the MySQL port is open. Also check MySQL's `bind-address` in `/etc/mysql/my.cnf` is set to `0.0.0.0` if remote connections are needed.
  2. Increase MySQL connection timeout temporarily: run `SET GLOBAL connect_timeout=60;` and `SET GLOBAL wait_timeout=600;` in MySQL, then update php.ini with `pdo_mysql.default_socket=` and restart PHP-FPM.

Dead Ends

Common approaches that don't work:

  1. 95% fail

    The error is a network-level timeout (MySQL connection timeout defaults to 30 seconds), not a PHP execution time limit. Changing execution time has no effect on the TCP handshake.

  2. 80% fail

    While this can delay the timeout, it may lead to resource exhaustion if the database remains unreachable, and the error will eventually reappear when the connection attempt exceeds the new limit.