MySQL Port

Summary: in this tutorial, you will learn about the default MySQL port, find the port that MySQL is using, and change the default port.

Default MySQL port

By default, MySQL uses port 3306 for communication between the client and the MySQL server. When you connect to a MySQL server, if you don’t specify a port, the client assumes the port 3306.

Finding MySQL port

You can find the port that the MySQL server is listening from the port variable or the MySQL configuration files.

MySQL configuration files

To find the port of MySQL server, you can check the MySQL configuration files. Their locations depend on your operating system.

Here are the common MySQL configuration locations:

  • Linux: /etc/my.cnf or /etc/mysql/my.cnf
  • Windows: C:\ProgramData\MySQL\MySQL Server X.X\my.ini
  • macOS: /etc/my.cnf or /usr/local/mysql/my.cnf.

Find the port variable in the [mysqld] section in the configuration:

[mysqld]
port=3306

MySQL variables

Alternatively, you can find the port number MySQL is currently running by showing the port variable if you are already connected to the MySQL server:

show global variables like 'port';Code language: PHP (php)

Output:

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)Code language: JavaScript (javascript)

Changing MySQL port

First, open the MySQL configuration file in a text editor.

Second, change the port under the [mysqld] section to a new port and save the configuration file.

[mysqld]
port=3301 # new portCode language: Shell Session (shell)

Third, restart the MySQL server for the changes to take effect.

Note that you need to ensure that the new port is not in use by other applications.

When you connect to a MySQL server using a non-default port, you need to use the -P or --porr option followed by the port number:

mysql -h <hostname> -P <port_number> -u <username> -p
Code language: HTML, XML (xml)

In this command:

  • <hostname> is the host of the MySQL server.
  • <port_number> is the port number on which MySQL is listening.
  • <username> is the user account you want to use for the connection.

The command will prompt you to enter the password for the specified username.

For example, the following command connects to the local MySQL server at the port 3301 with the root password:

mysql -h localhost -P 3301 -u root -p

Port security

When you open port 3306, you should restrict which IP addresses can access it so the MySQL server will not be accessible from untrusted hosts.

Summary

  • The default MySQL port is 3306.
  • The port variable stores the port that the MySQL server is currently using.
  • The port option under the [mysqld] section of the MySQL configuration file specifies the port to which the MySQL server is currently listening.
Was this tutorial helpful?