Table of Contents
What you will read?
SSH is one of the most used services on any Linux server, but leaving it on the default port (22) makes it a common target for automated attacks. Changing the SSH port is a simple way to reduce the number of brute-force login attempts and add a small layer of security.
Step 1: Choose and open a new port
Before changing anything, pick an unused port (between 1024–65535). You must allow it through the firewall so you don’t lose access:
sudo ufw allow 2222/tcp
You can replace 2222 with any number you prefer, as long as it’s not already in use.
Step 2: Edit the SSH configuration
Now update the SSH configuration file to use the new port instead of the default port 22:
sudo nano /etc/ssh/sshd_config
Find this line (or add it if missing):
Port 2222
Uncomment it by removing # if needed. Make sure only one Port line exists.
Step 3: Restart SSH service
After editing the config, you must restart the SSH service so the changes take effect:
sudo systemctl restart ssh
If there’s an error, check the syntax first:
sudo sshd -t
This helps you avoid misconfiguration that could lock you out.
Step 4: Test the new SSH port
Before closing your session, always test the new port from another terminal or system:
ssh -p 2222 youruser@your_server_ip
Only proceed to disable the old port after confirming the new one works.
Step 5: Close the default SSH port
Once you’ve successfully connected using the new port, you can block port 22 to reduce exposure to brute-force attacks:
sudo ufw delete allow 22/tcp
Keeping port 22 open after switching is a security risk — close it once everything is confirmed.
