How to Check MySQL Port on Unix/Linux Server: Multiple Methods Explained


5 views

When deploying applications to Unix servers, knowing your MySQL server's port is crucial for establishing database connections. While MySQL typically runs on port 3306 by default, administrators might configure it differently for various reasons.

The most reliable way to find the MySQL port is by examining its configuration file:

grep 'port' /etc/mysql/my.cnf
# Or for newer installations:
grep 'port' /etc/mysql/mysql.conf.d/mysqld.cnf

Example output might show:

port = 3306

For running MySQL instances, use netstat to identify active connections:

sudo netstat -tulnp | grep mysql

Sample output:

tcp6       0      0 :::3306       :::*          LISTEN      1234/mysqld

If you have MySQL client access, run this SQL query:

mysql -u root -p -e "SHOW VARIABLES LIKE 'port';"

This will prompt for password and return:

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+

Examine the MySQL process arguments:

ps aux | grep mysql

Look for --port parameter in the output.

If MySQL isn't using the default port, you'll need to specify it in your application's connection string. For example, in PHP:

$conn = new mysqli("localhost", "username", "password", "database", 3307);

If you can't connect, verify:

  • MySQL is actually running (sudo service mysql status)
  • The port isn't blocked by firewall (sudo ufw status)
  • MySQL is configured to listen on network interfaces

Remember that exposing MySQL on non-standard ports isn't a security measure by itself. Always:

  • Use strong passwords
  • Limit access with firewall rules
  • Consider SSH tunneling for remote connections

When deploying applications to Unix servers, verifying the MySQL port is crucial for proper database connectivity. Here are several reliable methods:


# Method 1: Check MySQL configuration file
sudo grep -i port /etc/mysql/my.cnf
# or for newer installations:
sudo grep -i port /etc/mysql/mysql.conf.d/mysqld.cnf

# Method 2: Check running processes
sudo netstat -tulnp | grep mysqld
# Alternative with ss:
sudo ss -tulnp | grep mysql

# Method 3: Query MySQL directly
mysql -u root -p -e "SHOW GLOBAL VARIABLES LIKE 'PORT';"

If you already have MySQL client access, these commands provide port information:


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+

# Or using status command which displays connection info:
mysql> \s
--------------
mysql  Ver 8.0.27 for Linux on x86_64
Connection id:          12345
Current database:
Current user:           root@localhost
SSL:                    Not in use
Current pager:          stdout
Using outfile:          ''
Using delimiter:        ;
Server version:         8.0.27-0ubuntu0.20.04.1 (Ubuntu)
Protocol version:       10
Connection:             Localhost via UNIX socket
Server characterset:    utf8mb4
Db     characterset:    utf8mb4
Client characterset:    utf8mb4
Conn.  characterset:    utf8mb4
UNIX socket:            /var/run/mysqld/mysqld.sock
Uptime:                 2 days 5 hours 3 min 27 sec

For automation scenarios, you might want to detect the port programmatically. Here's a Python example:


import subprocess
import re

def get_mysql_port():
    try:
        # Try reading from configuration
        result = subprocess.run(['sudo', 'grep', '-i', 'port', '/etc/mysql/my.cnf'], 
                              capture_output=True, text=True)
        if result.returncode == 0:
            match = re.search(r'port\s*=\s*(\d+)', result.stdout)
            if match:
                return int(match.group(1))
        
        # Fallback to process inspection
        result = subprocess.run(['sudo', 'netstat', '-tulnp'], 
                              capture_output=True, text=True)
        matches = re.finditer(r'tcp.*?([0-9.]+):(\d+).*?mysqld', result.stdout)
        for match in matches:
            return int(match.group(2))
        
        return 3306  # Default port
    
    except Exception as e:
        print(f"Error detecting MySQL port: {e}")
        return None

print(f"MySQL port: {get_mysql_port()}")

If you're unable to connect, consider these additional checks:


# Verify if the port is open
sudo iptables -L -n | grep 3306

# Check if MySQL is listening on the expected port
sudo lsof -i :3306

# Test telnet connection (if telnet is installed)
telnet localhost 3306