Few deployment blockers stall PHP, CodeIgniter 4, Node.js, or Laravel rollouts faster than seeing SQLSTATE[HY000] [1045] Access denied for user or SQLSTATE[HY000] [2002] Connection refused right after pushing code to staging or production. Although both errors happen before a single SQL query runs, they come from completely different network and authentication layers. Error 2002 means your PHP process never reached a listening MySQL/MariaDB server over TCP or a Unix socket, whereas Error 1045 means MySQL answered the socket—and rejected your username, host mask, password, or authentication plugin.
Diagnostic Matrix: Error 1045 vs Error 2002
Before guessing passwords or restarting Apache blindly, match the exact SQLSTATE[HY000] exception text against the cause and environment fix below:
| Exact Exception Message | Root Network / Auth Layer | Most Common Root Cause | Immediate Verified Fix |
|---|---|---|---|
[2002] No such file or directory |
Unix domain socket lookup | DB_HOST=localhost forces PHP PDO/MySQLi to look for /var/run/mysqld/mysqld.sock (fails in Docker or macOS Homebrew setups) |
Switch host to TCP 127.0.0.1 (or Docker service name mysql) |
[2002] Connection refused |
TCP handshake on port 3306 |
MySQL daemon stopped, listening on a custom port (3307), or Docker web container booted before DB finished initializing |
Start MariaDB/MySQL, verify bound port, or add Compose healthcheck |
[1045] Access denied for user 'root'@'localhost' (using password: YES) |
MySQL privilege table (mysql.user) |
Wrong password, missing quotes around special chars in .env, or Hostinger account-prefixed DB user omitted |
Quote password containing #/$ in .env; grant exact 'user'@'host' |
[1045] Access denied ... using password: NO |
Application environment loading | .env file missing, wrong key name, cached old config, or empty env var falling back to empty password |
Check .env readability and run php spark cache:clear / clear config cache |
Server sent charset unknown or authentication plugin failure |
MySQL 8 handshake plugin | Legacy client libraries lacking caching_sha2_password support over non-TLS sockets |
Upgrade PHP mysqlnd or configure explicit TLS / compatible grant |
1. The Hidden localhost vs 127.0.0.1 Trap in PHP
In C's libmysqlclient and PHP's mysqlnd driver, specifying localhost as the hostname is a special alias—it does not connect to loopback IP 127.0.0.1 over TCP port 3306. Instead, PHP silently switches transport to a local Unix socket file such as /tmp/mysql.sock or /var/run/mysqld/mysqld.sock.
Inside Docker containers, chrooted shared hosting accounts, or macOS environments where MySQL runs inside a separate container or non-standard socket directory, that Unix socket path does not exist inside the PHP container—producing SQLSTATE[HY000] [2002] No such file or directory even when MySQL is running healthily.
# Risky in Docker, macOS, and some Hostinger PHP containers (forces Unix socket lookup)
database.default.hostname = localhost
# Reliable: forces TCP/IP connection to loopback or container bridge
database.default.hostname = 127.0.0.1
database.default.port = 3306
Note the flip side when creating MySQL grants: MySQL treats 'appuser'@'localhost' (Unix socket) and 'appuser'@'127.0.0.1' (TCP loopback) as two separate user rows. If you switch PHP from localhost to 127.0.0.1, ensure your SQL user exists for '127.0.0.1' or '%', otherwise your 2002 socket error immediately turns into a 1045 access denied error.
2. Fixing Error 1045 & 2002 on Hostinger (`hPanel`)
Shared and Cloud plans on Hostinger enforce strict username prefixes and localhost scoping that catch developers migrating from local XAMPP or VPS setups:
- Keep the Account Prefix Intact: Creating database
technolilaunder hPanel IDu123456789produces database nameu123456789_technolilaand usernameu123456789_appuser. Using onlytechnolilaguarantees Error1045(or Error1044access denied to database). - Use
127.0.0.1When Application PHP Runs Separately: In Hostinger's web containers,127.0.0.1reliably connects over loopback without relying on specific container socket symlinks (while Hostinger's dashboard displayslocalhostfor phpMyAdmin). - Wrap Passwords Containing Special Characters in Double Quotes: In CodeIgniter 4 and Laravel
.envparsers, characters such as#start an inline comment, truncating your password silently at the first hash symbol! Wrap passwords in double quotes inside.envand inspect syntax using our Env Validator. - Check Remote MySQL Allowlists Only for External Tools: External clients connecting from your laptop or staging scripts require adding your public IP under Databases → Remote MySQL cleanly; leave web app PHP pointing to
127.0.0.1so traffic stays off public interfaces.
# Tested Hostinger CodeIgniter 4 .env database block
database.default.hostname = 127.0.0.1
database.default.database = u123456789_appdb
database.default.username = u123456789_appuser
database.default.password = "Strong#Pass$2026!"
database.default.DBDriver = MySQLi
database.default.port = 3306
database.default.charset = utf8mb4
database.default.DBCollat = utf8mb4_unicode_ci
3. Fixing Error 2002 & 1045 in Docker Compose
Inside a multi-container Docker network, 127.0.0.1 inside your PHP/Nginx container refers to the PHP container itself—never the separate MySQL container! Point DB_HOST to the exact service key from compose.yaml (for example db or mysql).
Second, Docker's depends_on: [db] only waits until the MySQL container process starts—not until InnoDB finishes initializing schema tables and opens port 3306. On a fresh volume, PHP containers often boot 5–10 seconds faster than MySQL, triggering intermittent Error 2002 Connection refused on startup.
services:
app:
build: .
environment:
DB_HOST: mysql
DB_PORT: "3306"
depends_on:
mysql:
condition: service_healthy
mysql:
image: mysql:8.4
environment:
MYSQL_DATABASE: app_db
MYSQL_USER: app_user
MYSQL_PASSWORD: secret_password
MYSQL_ROOT_PASSWORD: root_secret_password
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u$$MYSQL_USER", "-p$$MYSQL_PASSWORD"]
interval: 5s
timeout: 3s
retries: 10
If 1045 persists after adding healthchecks in Docker, remember that MySQL's entrypoint scripts (`MYSQL_USER`, `MYSQL_PASSWORD`) only run on an empty data volume. Changing passwords in compose.yaml after the first run requires either running ALTER USER manually inside MySQL or wiping the dev volume cleanly with docker compose down -v (never do -v against production data!).
4. Fixing Error 2002 / 1045 in Local XAMPP (Windows & macOS)
- Port
3306Conflicts: If Homebrew MySQL or Windows MySQL Service already binds port3306, XAMPP MariaDB either refuses to start or runs on3307(`my.ini`). Updatedatabase.default.port = 3307in.envor stop the conflicting local service. - Windows PowerShell / CLI PHP vs Apache PHP: CLI tools (
php spark migrate) sometimes pick up a different PHP binary or fail if Apache started MariaDB only after a port edit. Verify listening sockets cleanly withnetstat -ano | findstr 3306(Windows) orlsof -i :3306(macOS/Linux). - Blank Password Defaults vs Non-Empty
.env: Fresh local XAMPP leavesrootwith an empty password by default, whereas imported production `.env` configs hold a non-empty password—causing Error1045 (using password: YES)until aligned with a dedicated local grant.
5. Verifying Grants & Plugins Safely Inside MySQL 8.x
When credentials fail inconsistently between CLI and web workers, inspect the actual rows in mysql.user rather than guessing:
SELECT user, host, plugin, account_locked
FROM mysql.user
WHERE user = 'appuser';
-- Create explicit TCP + loopback-safe user with strict schema privileges
CREATE USER IF NOT EXISTS 'appuser'@'127.0.0.1'
IDENTIFIED BY 'Strong#Pass$2026!';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX
ON app_db.* TO 'appuser'@'127.0.0.1';
FLUSH PRIVILEGES;
Avoid granting ALL PRIVILEGES ON *.* or wide 'user'@'%' host wildcards on shared servers unless database firewalls isolate port 3306 cleanly from the public internet. Follow up with our CodeIgniter 4 database error troubleshooting guide, read our MySQL Error 1205 lock timeout fix, and explore more guides in the MySQL Hub.
6. Quick Verification Script in Pure PHP (PDO)
Before debugging full framework bootloaders, isolate connection failures in 15 lines of standalone PHP CLI/staging check (remove immediately after verification):
<?php
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=app_db;charset=utf8mb4';
try {
$pdo = new PDO($dsn, 'appuser', 'Strong#Pass$2026!', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_TIMEOUT => 5,
PDO::ATTR_EMULATE_PREPARES => false,
]);
echo 'Connected: ' . $pdo->query('SELECT VERSION()')->fetchColumn() . PHP_EOL;
} catch (PDOException $e) {
// Log error securely instead of echoing credentials in production
error_log('MySQL preflight check failed: ' . $e->getMessage());
exit(1);
}
Frequently Asked Questions
Why does mysql -u user -p succeed in SSH while PHP throws Error 1045?
The SSH CLI defaults to a Unix socket connection matching 'user'@'localhost', while your web app config may connect over 127.0.0.1 TCP (`'user'@'127.0.0.1'`), read a stale cached config value, or truncate an unquoted password containing # or $ in .env.
Why does Error 1045 show (using password: NO) when my .env clearly has a password?
Either PHP lacked read permission on .env, an environment cache loaded before you edited .env, Apache/PHP-FPM workers were not restarted after OS environment updates, or an array key typo left the password string empty (`''`).
Should I set DB_HOST to my live domain name (`technolila.com`)?
No—pointing DB_HOST at a CDN-proxied domain sends TCP traffic to Cloudflare or Hostinger HTTP edge proxies, which reject port 3306 immediately with Error 2002 Connection refused or timeouts. Always use internal loopback (`127.0.0.1`), a dedicated DB private IP, or an internal Docker service name.