How to Change the Default MySQL Port

By default, MySQL databases listen on port 3306. Changing this default port is a common practice to improve security through obscurity or to resolve port conflicts when running multiple database instances on the same server. This article provides a step-by-step guide on how to modify the MySQL configuration file, restart the database service, adjust firewall settings, and verify that your MySQL instance is successfully running on the new port.

Step 1: Locate and Edit the MySQL Configuration File

To change the port, you must edit the MySQL configuration file. The location of this file depends on your operating system:

Open the file in a text editor with administrative privileges. For example, on Linux, use:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Step 2: Update the Port Number

Within the configuration file, search for the [mysqld] section. This section defines the configuration for the MySQL server daemon.

Look for the port directive. If it is commented out with a # or does not exist, add or modify it to specify your new port (for example, 3307):

[mysqld]
port = 3307

(Optional) If you want local command-line clients to connect to the new port automatically without specifying it every time, locate the [client] section and update the port there as well:

[client]
port = 3307

Save the file and exit the text editor.

Step 3: Restart the MySQL Service

For the changes to take effect, you must restart the MySQL service.

Step 4: Configure the Firewall (If Applicable)

If your database needs to accept remote connections, you must open the new port in your system’s firewall and close the old port (3306).

Step 5: Verify the Port Change

To confirm that MySQL is now listening on the new port, connect to the database from the command line by explicitly stating the new port with the -P flag:

mysql -u root -p -P 3307

Once logged in, run the following SQL query to verify the port configuration:

SHOW VARIABLES LIKE 'port';

The output should display the new port number in the Value column:

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3307  |
+---------------+-------+