Database Connection Refused or Timeout
The database server is not reachable or took too long to respond.
Explanation
Database connection refused or timeout occurs when the application cannot establish a connection to the database server within the allowed time. This can happen because the database server is down, the host/port configuration is incorrect, network connectivity is broken, or the server is overloaded and not accepting new connections. Unlike a simple connection refused, a timeout means the server was reachable but didn't respond in time, often indicating resource exhaustion or network issues.
Common Causes
- Database server is down
- Wrong host/port configuration
- Firewall blocking connection
- Server overloaded with connections
- Network connectivity issue
Solution
Verify the database server is running (systemctl status mysql, pg_isready, etc.). Check the connection configuration (host, port, credentials) in your application. Test connectivity with command-line tools: mysql -h host -u user -p or psql -h host -U user. Check firewall rules and security groups for the database port. Monitor server resource usage (CPU, memory, connections). Increase connection timeout values in the database configuration if appropriate. Implement connection pooling for high-traffic applications.
Code Example
// Laravel database connection test
try {
DB::connection()->getPdo();
echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
// .env configuration
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=myapp
DB_USERNAME=root
DB_PASSWORD=secret
DB_TIMEOUT=60 // custom timeout
// Test with command line
// mysql -h 127.0.0.1 -P 3306 -u root -p
// psql -h 127.0.0.1 -p 5432 -U postgres
// Connection pooling in Node.js
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'secret',
database: 'myapp',
connectionLimit: 10,
connectTimeout: 60000,
});
Error Information
Language
php
Difficulty
Intermediate
Views
15
Related Errors
Laravel
Laravel Missing Application Encryption Key
The APP_KEY is not set or is invalid, preventing encryption operations.
DevOps
Laravel Schedule Task Failure
A scheduled task failed to execute or completed with errors.
PHP
Parse Error: Syntax Error
PHP detected a syntax error in the source code that prevents parsing.
PHP
Headers Already Sent
The code tries to send HTTP headers after output has already been sent to the browser.