Changing the default SSH port (22) is a simple but effective security measure that helps reduce automated attacks and unauthorised access attempts. This guide explains how to safely change your SSH port on a Linux server and avoid lockouts.
Table of Contents
Why Change the SSH Port?
By default, all Linux servers use port 22 for SSH. Attackers often scan this port to attempt brute-force logins.
- Reduces automated bot attacks
- Adds a basic layer of protection
- Helps secure the server from common vulnerabilities
Prerequisites
Before starting:
- Ensure you have root or sudo access
- Take a server backup or snapshot
- Keep your terminal session open until testing the new port
- Make sure your firewall allows the new port
Steps to Change the SSH Port
Step 1: Choose a New SSH Port
- Select a port between:
1024 – 65535 - Avoid using commonly used ports like 80, 443, 3306, etc.
- Example:
Use 2222 or 49152
Step 2: Update the SSH Configuration
- Open the SSH config file:
sudo nano /etc/ssh/sshd_config
- Find the line:
#Port 22
- Uncomment it and change to your new port:
Port 2222
- Save and exit.
Step 3: Adjust Firewall Rules
- For UFW
sudo ufw allow 2222/tcp sudo ufw delete allow 22/tcp
- For firewalld
sudo firewall-cmd --add-port=2222/tcp –permanent sudo firewall-cmd --remove-port=22/tcp –permanent sudo firewall-cmd –reload
- For iptables
sudo iptables -A INPUT -p tcp --dport 2222 -j ACCEPT sudo iptables -A INPUT -p tcp --dport 22 -j DROP
Step 4: Restart SSH Service
- Restart SSH to apply changes:
sudo systemctl restart sshd
- For CentOS/RHEL:
sudo systemctl restart sshd.service
Step 5: Test the New SSH Port
Open a new terminal window (keep the old one open in case of errors):
ssh -p 2222 user@your_server_ip
If the login is successful, the new port is active.
Troubleshooting
Cannot Connect After Changing Port?
- Check if the firewall allows the new port.
- Ensure SSH config syntax is correct:
sudo sshd -t
- Revert the port change using console or KVM access.
Security Best Practices (Recommended)
After changing the SSH port, also implement the following security measures:
- Disable root login to prevent unauthorised direct access.
- Use SSH key-based authentication instead of passwords.
- Enable Fail2Ban to block repeated failed login attempts.
- Restrict SSH access by IP (allow trusted IPs only).
- Keep all server packages and security patches up to date.
Conclusion
In this manner, changing your SSH port adds an extra layer of protection against automated attacks. Combine it with key security measures, SSH keys, disabling root login, Fail2Ban, and regular updates, to keep your server secure and stable.
If you need any help, our support team is always available to assist you.
A Linux VPS Hosting solution provides full root access and the flexibility needed to manage SSH settings, firewall rules and secure remote administration.
Want to go further with SSH security? Learn How to modify the SSH server port number