Change mysql default port number in linux

In this post we will learn about how to change mysql default port number in linux.This is a simple tip but it has many benefits.
Question: What are the benefits of changing the default port no. 3306 in mysql-server ?
Answer: For security point of view we generally change the port no. of MySQL Server so that attacker should not directly try to connect MySQL server on its default port that is 3306. We can prevent attacker by doing port scanning using iptable in Linux system (Read my this post)

To change the MySQL Server default port no. 3306,follow the given below steps.

Step 1: First of all check the desired port no. which is available in system. For eg. I am looking for port no. 3337 which should be free and not in use by any other process.


netstat -tanp |grep

Example. I am checking if port no. 3337 is free or not. In below command I got no result hence 3337 port no. is not used by any process.

root@ubuntu:~# netstat -tanp|grep 3337

Step 2: Now open the my.cnf file
In CentOS and Red Hat path is /etc/my.cnf
In Ubuntu and Debian path is /etc/mysql/my.cnf
If you still not able to find the my.cnf file use the command find / -name my.cnf
Note: mysql server package should be installed in system

In my.cnf find the [mysqld] section. Edit the port no. 3306 to 3337 or if you do not find any such line you can add port = 3337 in my.cnf but it should be under [mysqld] section

vi my.cnf

port = 3337

Step 3: Now restart the mysql service

In CentOS and Red Hat

service mysqld restart

In Ubuntu and Debian

service mysql restart 


/etc/init.d/mysql restart

Step 4: Now connect with mysql-server


mysql -u username -h FQDN-hostname-or-ipaddress -P port-number -p

Example: mysql -u root -h -P 3337 -p

2 thoughts on “Change mysql default port number in linux”

    • Same to me i am able to connect from both port … port is not validated … i am doing in 1 stand alone server


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.