How to Change the SSH Port on Ubuntu, Debian and AlmaLinux

Port 22 is the first target of automated password guessing. Changing the port does not make a server invulnerable, but it removes almost all background bot noise from the logs and lowers the load. The key is to do the steps in the right order so you do not lose access to the server.
Step 1. Pick a port
Any free port in the 1024–65535 range will do, for example 2222. Make sure it is not in use:
sudo ss -tlnp | grep 2222
Empty output means the port is free.
Step 2. Open the port in the firewall
Do this before changing the SSH settings.
UFW (Ubuntu, Debian):
sudo ufw allow 2222/tcp
firewalld (AlmaLinux, Rocky Linux, RHEL):
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
On systems with SELinux, also allow the SSH service to use the new port:
sudo semanage port -a -t ssh_port_t -p tcp 2222
If the semanage command is not found, install the policycoreutils-python-utils package.
Step 3. Change the port in the configuration
Open the settings file:
sudo nano /etc/ssh/sshd_config
Find the #Port 22 line, remove the # and set the new number:
Port 2222
Check that no file in /etc/ssh/sshd_config.d/ overrides the port:
grep -r "^Port" /etc/ssh/sshd_config.d/
Test the configuration for errors:
sudo sshd -t
Step 4. Apply the change
On Debian, AlmaLinux and most other systems, restarting the service is enough:
sudo systemctl restart ssh # Debian, Ubuntu
sudo systemctl restart sshd # AlmaLinux, Rocky Linux, RHEL
The Ubuntu quirk
On recent Ubuntu releases the port is held not by the service itself but by the ssh.socket unit, and a plain restart of ssh does not change the port. Check whether the socket is in use:
systemctl is-active ssh.socket
If the answer is active, run:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socket
Step 5. Test the connection
Confirm that the service listens on the new port:
sudo ss -tlnp | grep ssh
In a second terminal window, connect on the new port:
ssh -p 2222 root@203.0.113.10
Only after a successful login close the old port:
sudo ufw delete allow 22/tcp
If you lose access
Open the server console in your hosting control panel (VNC) — it works independently of SSH. Log in, put Port 22 back in sshd_config and restart the service.
Skip typing the port every time
Add the server to ~/.ssh/config on your computer:
Host myserver
HostName 203.0.113.10
User root
Port 2222
Now ssh myserver is enough.
What else to do for SSH security
Changing the port is only the first step. Real protection comes from key-based login with passwords disabled, Fail2Ban and two-factor authentication.


