Moving SSH off port 22 does not make a server secure by itself, but it removes most automated login noise from your logs. The risk is getting the order wrong and locking yourself out, so follow these steps exactly. We use port 2222 as the example.
Warning: Keep one SSH session open the whole time. Open the new port in the firewall before SSH starts using it, and only close port 22 after the new port is proven to work.
1. Open the new port in the firewall
Ubuntu and Debian with UFW:
sudo ufw allow 2222/tcpAlmaLinux and Rocky Linux with firewalld:
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload2. Allow the port in SELinux (AlmaLinux and Rocky only)
SELinux only lets SSH bind to approved ports:
sudo dnf install -y policycoreutils-python-utils
sudo semanage port -a -t ssh_port_t -p tcp 22223. Listen on both ports for now
Open the main configuration file:
sudo nano /etc/ssh/sshd_configFind the line #Port 22 and replace it with:
Port 22
Port 2222Make sure no file in /etc/ssh/sshd_config.d/ sets Port as well: grep -ri '^port' /etc/ssh/sshd_config.d/. Then check the syntax:
sudo sshd -t4. Apply the change
Ubuntu 24.04 starts SSH through a systemd socket. Check with systemctl is-enabled ssh.socket. If it says enabled, run:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socketUbuntu 22.04 and Debian 12:
sudo systemctl restart sshAlmaLinux and Rocky Linux:
sudo systemctl restart sshdConfirm both ports are listening:
sudo ss -tlnp | grep -E ':22 |:2222 '5. Test the new port
From a new terminal on your computer:
ssh -p 2222 alex@203.0.113.256. Remove port 22
Once the test works, delete the Port 22 line, repeat step 4, and close the old port:
sudo ufw delete allow OpenSSH # UFW
sudo firewall-cmd --permanent --remove-service=ssh && sudo firewall-cmd --reload # firewalld7. Update everything that connects
- Your
~/.ssh/config: setPort 2222. - Fail2ban: add
port = 2222under[sshd]injail.local. - SFTP clients such as WinSCP or FileZilla, backup scripts and CI jobs.
Troubleshooting
- Connection refused on 2222: SSH is not listening there. On Ubuntu 24.04 you probably restarted
sshinstead ofssh.socket. On AlmaLinux/Rocky check the SELinux step:sudo journalctl -u sshd -n 20. - Connection timed out on 2222: the firewall is still blocking it. Re-check step 1.
- Locked out completely: use the browser console from Open Control Panel, put
Port 22back and restart SSH.
