Fix "MySQL connection refused port 3306" Error

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.

MySQL Node.js Python PHP Java Laravel Django

What This Error Looks Like

mysql Command Line Error:
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")
Node.js / mysql2 Error:
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)
Python / mysql-connector Error:
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)")
PHP / PDO Error:
PDOException: SQLSTATE[HY000] [2002] Connection refused

Warning: mysqli_connect(): (HY000/2002): Connection refused in /var/www/html/index.php on line 5
Java / JDBC Error:
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)

Quick Fix (Choose Your Operating System)

The Problem: MySQL server is not running on port 3306

  1. Open Services app: Press Win + R, type services.msc
  2. Find "MySQL80" service (or your version number)
  3. Right-click → Start
  4. Test: mysql -h localhost -u root -p
  1. Open Terminal
  2. Start MySQL: brew services start mysql
  3. Verify: mysql -h localhost -u root -p
  4. Or check: brew services list
  1. Open Terminal
  2. Start MySQL: sudo systemctl start mysql
  3. Verify: mysql -h localhost -u root -p
  4. Check status: sudo systemctl status mysql

Complete Troubleshooting Guide

1 Understand the Error

Connection refused on port 3306 means:

  • MySQL server is not running (most common - 85% of cases)
  • MySQL is running on a different port
  • MySQL is bound to a different IP address
  • Firewall is blocking port 3306
  • MySQL reached max_connections limit
Key Point: Port 3306 is MySQL's default port. If nothing responds on this port, your application cannot connect.

2 Check if MySQL is Running

Check MySQL Status on Windows

cmd
# 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

Check MySQL Status on macOS

bash
# 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)

Check MySQL Status on Linux

bash
# 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

3 Start MySQL Server

Start MySQL on Windows

Method 1: Services GUI (Easiest)

  1. Press Win + R, type services.msc, press Enter
  2. Find "MySQL80" (or your version number like MySQL57, MySQL84)
  3. Right-click → "Start"
  4. Optional: Right-click → "Properties" → Set "Startup type" to "Automatic"

Method 2: Command Line (Run as Administrator)

cmd
# 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.

Start MySQL on macOS

Method 1: Using Homebrew Services (Recommended)

bash
# Start MySQL and run at login (persistent)
brew services start mysql

# Check status
brew services list

Method 2: Manual Start (Foreground)

bash
# Start MySQL manually (runs in foreground)
mysql.server start

# Stop MySQL
mysql.server stop

# Restart MySQL
mysql.server restart
If MySQL isn't installed:
# Install MySQL via Homebrew
brew install mysql

# Then start it
brew services start mysql

Start MySQL on Linux

Using systemctl (Ubuntu/Debian/CentOS/RHEL)

bash
# 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
If MySQL is not installed:
# 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

4 Verify MySQL is Listening on Port 3306

After starting MySQL, confirm it's actually listening on port 3306.

bash
# 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)
If you don't see port 3306: MySQL is configured to use a different port. Check /etc/mysql/my.cnf (Linux), /etc/my.cnf (macOS), or C:\ProgramData\MySQL\MySQL Server 8.0\my.ini (Windows) for the port setting.

5 Test MySQL Connection

Using mysql Command Line

bash
# 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

Test from Your Application

Node.js / mysql2:

javascript
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:

python
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
<?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";
}
?>

6 Configure MySQL (If Needed)

Check MySQL configuration file for connection settings.

bash
# 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
bind-address Setting: If set to 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.

Common Issues and Solutions

Issue 1: mysql Command Works But Application Doesn't

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:

bash
# 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

Issue 2: "Too Many Connections"

Symptoms: MySQL refuses new connections even though it's running

Cause: Reached max_connections limit

Solutions:

sql
-- 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

Issue 3: MySQL Running on Different Port

Check which port MySQL is actually using:

bash
# 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.

Issue 4: Firewall Blocking Port 3306

Allow port 3306 through firewall:

bash
# 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

Issue 5: MySQL in Docker Container

If using MySQL in Docker:

bash
# 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:

yaml
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:

Quick Reference Commands

cheatsheet
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

Still Having Issues?

Debugging checklist:

Visit our Interactive Diagnostic Wizard for personalized help.