Skip to main content

How to change SSH Port?

This tutorial will provide you with a few simple steps on how to change your server's SSH port from default 22 to any other port.

Updated over 3 weeks ago

Changing the default SSH port is strongly recommended to enhance your server’s security. Please take note that a new port number should not be used by any other service or be blocked by your server firewall rules.

To change SSH port on operating systems mentioned above, complete the following steps:

1. Login to Your Server

Connect via SSH as the root user. You can do it via terminal/shell or use SSH client, for example, PuTTY.

2. Edit the SSH Configuration File

Open the SSH configuration file:

vi /etc/ssh/sshd_config

Find the following line:

#Port 22

Remove the # at the beginning of the line and change "22" into your wanted port number (e.g., 2222).

Port 2222

Save the file and exit (press "Esc", then type :wq and click "Enter").

However, on Ubuntu 24.04, you’ll need to perform a few additional steps:

Open ssh.socket file:

nano /etc/systemd/system/sockets.target.wants/ssh.socket

Inside it, you’ll see a section like:

[Socket]
ListenStream=22
Accept=no
FreeBind=yes

You have to change it to your desired port, e.g.:

[Socket]
ListenStream=
ListenStream=2222
Accept=no
FreeBind=yes

Then reload and restart systemd’s socket unit:

systemctl daemon-reload
systemctl restart ssh.socket

2. Restart the SSH Service

Restart the SSH service to apply changes.

On AlmaLinux/Rocky Linux run this command:

systemctl restart sshd

On Ubuntu/Debian run this:

systemctl restart ssh

3. Adjust Firewall Rules

Replace 2222 with your chosen port in these steps.

3.1. Iptables (default firewall)

If you’re using iptables, run the following command:

iptables -A INPUT -p tcp --dport 2222 -j ACCEPT

To save changes, on Ubuntu/Debian run these commands:

netfilter-persistent save
netfilter-persistent reload

On RHEL (AlmaLinux/Rocky Linux) run these comands to save changes:

service iptables save
service iptables restart

3.2 Firewalld (AlmaLinux, Rocky Linux)

If you’re using firewalld, run the following commands:

firewall-cmd --permanent --add-port=2222/tcp
firewall-cmd --reload

3.3. UFW (Ubuntu, Debian)

If you’re using UFW, run the following commands:

ufw allow 2222/tcp
ufw reload

4. Test the New SSH Port

Open a new terminal session (keep the old one open) and test the new port (replace 2222 to your specified port):

ssh -p 2222 root@your_server_ip

Once confirmed successful, you can safely close the original session.

Did this answer your question?