How to change the SSH port
Kort antwoord
Edit /etc/ssh/sshd_config, change the Port line to your chosen port, open that port in your firewall, then restart the SSH service. Two extra steps catch people out: recent Ubuntu releases set the port on ssh.socket instead, and RHEL-family distributions need the new port labelled in SELinux first.
Moving SSH off port 22 doesn't make your server unbreakable, but it does cut down sharply on the automated scanning traffic that hits every server on the default port. Use it alongside key-based authentication and the other steps in How to improve your SSH security, not instead of them.
Change the port
Choose a port
Pick an unused port above 1024 to avoid the reserved system port range. Check it isn't already used by another service on the server.
Edit sshd_config
Open /etc/ssh/sshd_config in a text editor and find the Port line. Uncomment it if needed, and set it to your chosen port number.
Port 2222On recent Ubuntu releases, check for socket activation first. From Ubuntu 22.10 onwards, sshd is started by a systemd socket unit. When that unit is active, the Port directive in sshd_config is ignored and the listening port comes from the socket instead, so the change appears to work but nothing moves. Check it:
systemctl is-enabled ssh.socketIf that returns enabled, set the port on the socket as well:
sudo systemctl edit ssh.socketAdd the following, clearing the inherited value first:
[Socket]
ListenStream=
ListenStream=2222Then reload and restart the socket:
sudo systemctl daemon-reload
sudo systemctl restart ssh.socketAllow the new port through the firewall
Open the new port in whatever firewall the server runs, for example UFW, firewalld, or iptables, before you restart SSH. Leave the old port open until you've confirmed the new one works.
# UFW example
sudo ufw allow 2222/tcpRestart the SSH service
On RHEL-family distributions, tell SELinux about the port first. On AlmaLinux, Rocky Linux, CentOS Stream and Oracle Linux, SELinux is enforcing by default and will not let sshd bind to a port outside its own policy, so the restart fails with a permission or bind error. Label the new port before restarting:
sudo dnf install policycoreutils-python-utils
sudo semanage port -a -t ssh_port_t -p tcp 2222Check the configuration for syntax errors, then restart:
sudo sshd -t
sudo systemctl restart sshdOn Debian and Ubuntu the service is called ssh rather than sshd. If you changed ssh.socket in step 2, restarting the socket is what puts the new port into effect.
Test before you disconnect
Open a new terminal window and connect on the new port without closing your existing session:
ssh -p 2222 user@your-server-ipOnly close your original session once the new connection works. If it fails, your existing session lets you fix the configuration without being locked out.
Remove the old port from the firewall
Once you've confirmed the new port works, remove the rule allowing the old port (22) so it's no longer reachable.