Getting the "MySQL connection refused port 3306" error in your Node.js, Python, PHP, or Java application? This complete guide shows you how to start MySQL server and fix connection issues on Windows, macOS, and Linux.
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) ERROR 2003 (HY000): Can't connect to MySQL server on 'localhost' (10061) ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1:3306' (111 "Connection refused")
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1144:16)
Error: getaddrinfo ECONNREFUSED localhost:3306
at Protocol._enqueue (node_modules/mysql2/lib/protocol/sequences/connection.js:82:16)
mysql.connector.errors.DatabaseError: 2003 (HY000): Can't connect to MySQL server on 'localhost:3306' (111 Connection refused) pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '127.0.0.1' ([Errno 111] Connection refused)")
PDOException: SQLSTATE[HY000] [2002] Connection refused Warning: mysqli_connect(): (HY000/2002): Connection refused in /var/www/html/index.php on line 5
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago.
java.net.ConnectException: Connection refused (Connection refused)
at java.base/java.net.PlainSocketImpl.socketConnect(Native Method)
The Problem: MySQL server is not running on port 3306
Win + R, type services.mscmysql -h localhost -u root -pbrew services start mysqlmysql -h localhost -u root -pbrew services listsudo systemctl start mysqlmysql -h localhost -u root -psudo systemctl status mysqlConnection refused on port 3306 means:
# Method 1: Check if MySQL process is running tasklist | findstr mysql # Method 2: Check if port 3306 is listening netstat -an | findstr :3306 # Method 3: Check service status sc query MySQL80 # Method 4: Try connecting with mysql client mysql -h localhost -u root -p
Expected Output if Running:
mysqld.exe 5432 Console 1 145,678 K TCP 0.0.0.0:3306 0.0.0.0:0 LISTENING SERVICE_NAME: MySQL80 STATE : 4 RUNNING
# Method 1: Using Homebrew services brew services list | grep mysql # Method 2: Check process ps aux | grep mysqld # Method 3: Check if port 3306 is listening lsof -i :3306 # Method 4: Try connecting mysql -h localhost -u root -p
Expected Output if Running:
mysql started username ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist mysqld 12345 user 6u IPv4 0x... TCP *:mysql (LISTEN)
# Method 1: Using systemctl sudo systemctl status mysql # Or for some distributions: sudo systemctl status mysqld # Method 2: Check process ps aux | grep mysqld # Method 3: Check if port 3306 is listening sudo lsof -i :3306 # or sudo netstat -tulpn | grep :3306 # Method 4: Try connecting mysql -h localhost -u root -p
Expected Output if Running:
● mysql.service - MySQL Community Server Loaded: loaded (/lib/systemd/system/mysql.service; enabled) Active: active (running) since Mon 2024-01-15 10:30:00 UTC mysqld 12345 0.5 2.1 /usr/sbin/mysqld
Method 1: Services GUI (Easiest)
Win + R, type services.msc, press EnterMethod 2: Command Line (Run as Administrator)
# Start MySQL service net start MySQL80 # Enable auto-start on boot sc config MySQL80 start=auto
Method 3: XAMPP/WAMP Control Panel
If you installed MySQL via XAMPP or WAMP, use their control panel to start MySQL service.
Method 1: Using Homebrew Services (Recommended)
# Start MySQL and run at login (persistent) brew services start mysql # Check status brew services list
Method 2: Manual Start (Foreground)
# Start MySQL manually (runs in foreground) mysql.server start # Stop MySQL mysql.server stop # Restart MySQL mysql.server restart
# Install MySQL via Homebrew brew install mysql # Then start it brew services start mysql
Using systemctl (Ubuntu/Debian/CentOS/RHEL)
# Start MySQL sudo systemctl start mysql # Or for some distributions: sudo systemctl start mysqld # Enable auto-start on boot sudo systemctl enable mysql # Check status sudo systemctl status mysql # Restart MySQL sudo systemctl restart mysql
# Ubuntu/Debian sudo apt-get update sudo apt-get install mysql-server # CentOS/RHEL sudo yum install mysql-server # Then start it sudo systemctl start mysql
After starting MySQL, confirm it's actually listening on port 3306.
# Windows netstat -an | findstr :3306 # macOS/Linux lsof -i :3306 # or netstat -an | grep 3306
Expected Output:
# You should see MySQL listening on 3306: TCP 0.0.0.0:3306 0.0.0.0:0 LISTENING TCP [::]:3306 [::]:0 LISTENING # Or with lsof: mysqld 12345 mysql 20u IPv4 0x... TCP *:mysql (LISTEN)
/etc/mysql/my.cnf (Linux), /etc/my.cnf (macOS), or C:\ProgramData\MySQL\MySQL Server 8.0\my.ini (Windows) for the port setting.
# Test basic connection mysql -h localhost -u root -p # Connect to specific database mysql -h localhost -u root -p mydatabase # Test with explicit port mysql -h 127.0.0.1 -P 3306 -u root -p
Node.js / mysql2:
const mysql = require('mysql2');
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'yourpassword',
database: 'mydatabase'
});
connection.connect((err) => {
if (err) {
console.error('✗ MySQL connection error:', err.message);
return;
}
console.log('✓ MySQL connected successfully');
connection.end();
});
Python / mysql-connector:
import mysql.connector
try:
conn = mysql.connector.connect(
host="localhost",
port=3306,
user="root",
password="yourpassword",
database="mydatabase"
)
print("✓ MySQL connected successfully")
conn.close()
except Exception as e:
print(f"✗ MySQL connection error: {e}")
PHP / PDO:
<?php
try {
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=mydatabase', 'root', 'yourpassword');
echo "✓ MySQL connected successfully\n";
} catch (PDOException $e) {
echo "✗ MySQL connection error: " . $e->getMessage() . "\n";
}
?>
Check MySQL configuration file for connection settings.
# Find my.cnf location: # Linux: /etc/mysql/my.cnf or /etc/my.cnf # macOS: /etc/my.cnf or /opt/homebrew/etc/my.cnf # Windows: C:\ProgramData\MySQL\MySQL Server 8.0\my.ini # Important settings to check: [mysqld] bind-address = 127.0.0.1 # Allow connections from localhost port = 3306 # Default MySQL port max_connections = 151 # Maximum simultaneous connections
127.0.0.1, MySQL only accepts local connections. To allow connections from other machines, set to 0.0.0.0 (not recommended for production without proper security). After changing, restart MySQL service.
Symptoms: mysql -u root -p works, but your app gets connection refused
Cause: mysql client may use Unix socket, your app uses TCP/IP
Solutions:
# Force mysql client to use TCP/IP mysql -h 127.0.0.1 -u root -p # If this fails, MySQL isn't listening on TCP/IP # Check bind-address in my.cnf: grep bind-address /etc/mysql/my.cnf # Should show: bind-address = 127.0.0.1 or 0.0.0.0 # Restart MySQL after config changes
Symptoms: MySQL refuses new connections even though it's running
Cause: Reached max_connections limit
Solutions:
-- Check current connections SHOW STATUS WHERE variable_name = 'Threads_connected'; SHOW VARIABLES LIKE 'max_connections'; -- Temporarily increase limit (requires SUPER privilege) SET GLOBAL max_connections = 200; -- Permanently: Edit my.cnf and add/change under [mysqld]: [mysqld] max_connections = 200 -- Then restart MySQL
Check which port MySQL is actually using:
# Check MySQL configuration grep port /etc/mysql/my.cnf # Check which ports MySQL is listening on sudo lsof -i -P | grep mysql # or sudo netstat -tulpn | grep mysql
If MySQL is on a different port, update your connection string to match.
Allow port 3306 through firewall:
# Windows - Allow port 3306 netsh advfirewall firewall add rule name="MySQL" dir=in action=allow protocol=TCP localport=3306 # Linux (Ubuntu/Debian) - Allow port 3306 sudo ufw allow 3306/tcp # macOS - Check firewall settings # System Preferences → Security & Privacy → Firewall
If using MySQL in Docker:
# Check if MySQL container is running docker ps | grep mysql # If not running, start it docker start mysql-container # Or run a new MySQL container docker run -d -p 3306:3306 --name mysql \ -e MYSQL_ROOT_PASSWORD=yourpassword \ mysql:8.0 # Check container logs docker logs mysql-container # Connect to MySQL in Docker docker exec -it mysql-container mysql -u root -p
Docker Compose example:
version: '3.8'
services:
mysql:
image: mysql:8.0
ports:
- "3306:3306"
environment:
MYSQL_ROOT_PASSWORD: yourpassword
MYSQL_DATABASE: mydatabase
restart: always
volumes:
- mysql-data:/var/lib/mysql
volumes:
mysql-data:
MYSQL SERVICE COMMANDS BY OS ============================= Windows: Check: sc query MySQL80 Start: net start MySQL80 Stop: net stop MySQL80 Restart: net stop MySQL80 && net start MySQL80 CLI: mysql -h localhost -u root -p macOS (Homebrew): Check: brew services list | grep mysql Start: brew services start mysql Stop: brew services stop mysql Restart: brew services restart mysql CLI: mysql -h localhost -u root -p Linux (systemd): Check: sudo systemctl status mysql Start: sudo systemctl start mysql Stop: sudo systemctl stop mysql Enable: sudo systemctl enable mysql Restart: sudo systemctl restart mysql CLI: mysql -h localhost -u root -p VERIFY MYSQL ============ Port check: lsof -i :3306 (Mac/Linux) | netstat -an | findstr :3306 (Win) Test connect: mysql -h localhost -u root -p Connection URL: mysql://root:password@localhost:3306/database CONFIGURATION FILES =================== Linux: /etc/mysql/my.cnf macOS: /etc/my.cnf or /opt/homebrew/etc/my.cnf Windows: C:\ProgramData\MySQL\MySQL Server 8.0\my.ini
Debugging checklist:
mysql -h localhost -u root -pVisit our Interactive Diagnostic Wizard for personalized help.