Security

Change the SSH port safely without locking yourself out

Move SSH to another port in the right order: firewall first, SELinux and Ubuntu socket activation handled, both ports tested, then port 22 closed.

IntermediateLinux server3 min read

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:

Bash
sudo ufw allow 2222/tcp

AlmaLinux and Rocky Linux with firewalld:

Bash
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload

2. Allow the port in SELinux (AlmaLinux and Rocky only)

SELinux only lets SSH bind to approved ports:

Bash
sudo dnf install -y policycoreutils-python-utils
sudo semanage port -a -t ssh_port_t -p tcp 2222

3. Listen on both ports for now

Open the main configuration file:

Bash
sudo nano /etc/ssh/sshd_config

Find the line #Port 22 and replace it with:

Port 22
Port 2222

Make 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:

Bash
sudo sshd -t

4. Apply the change

Ubuntu 24.04 starts SSH through a systemd socket. Check with systemctl is-enabled ssh.socket. If it says enabled, run:

Bash
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

Ubuntu 22.04 and Debian 12:

Bash
sudo systemctl restart ssh

AlmaLinux and Rocky Linux:

Bash
sudo systemctl restart sshd

Confirm both ports are listening:

Bash
sudo ss -tlnp | grep -E ':22 |:2222 '

5. Test the new port

From a new terminal on your computer:

Bash
ssh -p 2222 alex@203.0.113.25

6. Remove port 22

Once the test works, delete the Port 22 line, repeat step 4, and close the old port:

Bash
sudo ufw delete allow OpenSSH                               # UFW
sudo firewall-cmd --permanent --remove-service=ssh && sudo firewall-cmd --reload   # firewalld

7. Update everything that connects

  • Your ~/.ssh/config: set Port 2222.
  • Fail2ban: add port = 2222 under [sshd] in jail.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 ssh instead of ssh.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 22 back and restart SSH.

Next steps

Was this guide helpful?

Still stuck?

Ask MdmHost AI for a quick answer, or open a ticket and our team will take a look. We are here 24/7.