SSH port in Ubuntu
How To

How to Change SSH port in Ubuntu

Sagar Sharma
Sagar Sharma

Table of Contents

The SSH uses port number 22 by default and there are plenty of reasons why you want to change it.

Whether you're running multiple VMs locally or want to have a little peace of mind with bots attacking this famous port, changing SSH port has its legit usage.

If you are doing it on a remote server, please ensure that there is no firewall or if there is a firewall, allow the new port in firewall rules before changing the SSH port. Otherwise, you may not be able to access the system via SSH in some cases. 

Change the SSH port in Ubuntu VM

If you haven't configured SSH yet, I'd highly recommend the other guide explaining how to configure SSH the easy way!

So the first step of configuring SSH in Ubuntu VM will be logging in remotely (obviously!):

ssh user@server_IP 

To change the default SSH port, you'll have to make some changes in the file located at /etc/ssh/sshd_config:

sudo nano /etc/ssh/sshd_config

Now, you have to look for #Port 22, uncomment it (by removing #) and change the port no. to the desired number. I'm going for port no. 2222 here:

Changing default SSH port in Ubuntu

Now, you have to reload the sshd_config so recently made changes can take effect:

sudo systemctl reload sshd

Changing rules for Firewall

This part will only be applicable to those who have configured a firewall to their system.

So let's start with allowing port through UFW:

sudo ufw allow 2222/tcp

Now, let's add the rule of accepting TCP port 2222 in IPTables:

sudo /sbin/iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 2222 -j ACCEPT

Connecting to Server after changing the SSH port

You tried connecting to your VM after changing the default SSH port and it throws an error saying "port 22: Connection refused"?

port 22: Connection refused

Don't worry, your precious VM is still safe!

You just have to mention the new port with -p option while executing the SSH command:

ssh -p 2222 user@localhost
changed thr default ssh port to 2222

And you successfully changed your default SSH port to 2222!


This was my take on how to change the default port in your Ubuntu VM. And if you have any queries, feel free to SSH in the comments!