Correct Way to Change SSH Port on Ubuntu (Oracle Cloud Guide)

I recently changed the SSH port on my Ubuntu VM hosted on Oracle Cloud and found myself locked out. After searching online, I came across this article:
🔗 AskUbuntu - Can't log in after changing default port 22 on Oracle Cloud VM
However, the article didn't provide a clear solution, so I kept testing different approaches until I found the correct fix.
Understanding the Issue
By default, Ubuntu on Oracle Cloud uses iptables instead of ufw, which means manually changing the SSH port in /etc/ssh/sshd_config
is not enough. You must also update firewall rules accordingly.
The Correct Way to Change the SSH Port
1️⃣ Edit the SSH Configuration File
Find the line that specifies the port and change it:
Port 2222 # Replace with your desired port
2️⃣ Allow the New SSH Port in iptables
🔹 The number 6 represents the position where this rule should be inserted. It must be placed above the reject-all rule.
To check existing rules and determine the correct line number, use:
3️⃣ Save the iptables Configuration
4️⃣ Restart the SSH Service
Updating Oracle Cloud Firewall Rules
After configuring iptables, you must also update the security rules in the Oracle Cloud web portal:
- Navigate to:
Networking > Virtual Cloud Networks > [Your VCN] > Security Lists > [Default Security List] - Click Add Ingress Rules and enter the following:
- Source Type: CIDR
- Source CIDR:
0.0.0.0/0
- IP Protocol: TCP
- Source Port Range: All
- Destination Port Range:
2222
(or the port you set in SSH and iptables)
- Save the changes.
Connecting via SSH
Now, you can connect using the new port:
Cleaning Up Old Rules
Once you've successfully connected using the new port, you can remove the old rule for port 22:
🔹 Replace 8 with the correct line number for the old port 22 rule (check using iptables -L INPUT --line-numbers
).
You may also remove the old Ingress Rule for port 22 in Oracle Cloud's security settings.
Conclusion
This method ensures a proper SSH port change without getting locked out of your Oracle Cloud Ubuntu VM. Hope this helps! 🚀