How to Change SSH Port in Ubuntu

Changing the default SSH port (22) on Ubuntu Linux is a highly recommended security practice that helps protect your server from automated brute-force attacks. This guide provides a straightforward, step-by-step walkthrough on how to modify the SSH configuration file, update your firewall rules to prevent being locked out, and restart the SSH service to apply the changes safely.

Step 1: Choose a New Port Number

Before making changes, select a new port number. It is best to choose a port between 1024 and 65535 to avoid conflicts with other well-known system services. Ensure the port you choose is not currently in use by another service on your system.

Step 2: Configure the Firewall

Before changing the SSH port, you must configure your firewall to allow traffic through the new port. If you skip this step, you will be locked out of your server.

If you are using the default Uncomplicated Firewall (UFW) on Ubuntu, run the following command (replace 2222 with your chosen port):

sudo ufw allow 2222/tcp

If the firewall is currently enabled, reload it to apply the changes:

sudo ufw reload

Step 3: Modify the SSH Configuration File

Next, edit the SSH daemon configuration file using a text editor like Nano:

sudo nano /etc/ssh/sshd_config

Scroll through the file to find the line that reads:

#Port 22

Uncomment the line by removing the # symbol, and change the number 22 to your new port number:

Port 2222

Save and exit the file. In Nano, you can do this by pressing Ctrl + O, hitting Enter, and then pressing Ctrl + X.

(Note: On newer Ubuntu versions using systemd socket activation for SSH, you may also need to edit the socket configuration file at /lib/systemd/system/ssh.socket to match the new port).

Step 4: Restart the SSH Service

Apply the new configuration by restarting the SSH daemon with the following command:

sudo systemctl restart ssh

Step 5: Verify the Connection

Important: Do not close your current terminal session. If something went wrong, closing the session could lock you out permanently.

Open a new, separate terminal window on your local machine and attempt to log in using the new port:

ssh -p 2222 username@your_server_ip

If the login is successful, you have correctly configured the new port.

Step 6: Close the Old Port

Now that you have verified the new connection works, you can safely remove the firewall rule for the old default port (22) to block unauthorized access:

sudo ufw delete allow 22/tcp
sudo ufw reload