Short answer: the order matters more than the commands. Allow the new port in the firewall first, set Port 2222 in a drop-in file such as /etc/ssh/sshd_config.d/port.conf, apply it, test from a second terminal while your current session stays open, and only then close port 22. On Ubuntu 24.04 “apply it” means sudo systemctl daemon-reload && sudo systemctl restart ssh.socket, not restarting the service, or sshd quietly keeps listening on 22. On Rocky Linux, SELinux and firewalld both have to be told about the new port as well.
sudo ufw allow 2222/tcp # 1. firewall first
echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/port.conf # 2. new port
sudo sshd -t && sudo systemctl daemon-reload && sudo systemctl restart ssh.socket # 3. apply
ssh -p 2222 you@203.0.113.10 # 4. test from a NEW terminal
sudo ufw delete allow OpenSSH # 5. only now close 22Which port should I pick?
Any free TCP port works. A few rules keep you out of trouble:
- Do not take a port another service uses or might use later, such as 3306 (MySQL), 5432 (PostgreSQL), 3389 (RDP), 8080 or 8443; the common ports list shows which numbers are spoken for. Check that nothing listens on your choice:
sudo ss -tlnp | grep ':2222 'should print nothing. - Stay out of 32768–60999. Linux uses that range for its own outgoing connections, so a service listening there can collide with them.
- Below 1024 is fine too. Only root may bind those ports, so no ordinary user process can grab the port if sshd is ever down. 222 is one example.
- Think about where you connect from. Hotel, campus and office networks often block unusual outgoing ports. Test from those networks before you rely on it.
The examples below use 2222. Replace it with your choice everywhere.
How do I change the SSH port on Ubuntu 24.04?
Since Ubuntu 22.10, OpenSSH is socket-activated: systemd itself listens on the port through ssh.socket and starts sshd when a connection arrives. On 24.04 a generator reads Port and ListenAddress from the sshd configuration and builds the socket from them, but only when systemd reloads. That is the whole trap.
- 1Allow the new port in the firewall
ufw sudo ufw status # is ufw active at all? sudo ufw allow 2222/tcpIf your provider has a network firewall or security group in front of the server, open 2222 there as well. The UFW guide covers the rest of the rule set.
- 2Set the port in a drop-in file
new port echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/port.conf grep -n '^Port' /etc/ssh/sshd_config # should print nothingA drop-in survives package upgrades that replace
sshd_config. Thegrepmatters: if the main file has an uncommentedPort 22, sshd listens on both ports, becausePortlines add up instead of replacing each other. Comment it out. - 3Check the config and apply it
Ubuntu 24.04 sudo sshd -t # prints nothing when OK sudo systemctl daemon-reload # re-runs the socket generator sudo systemctl restart ssh.socketYour current session stays open: restarting the socket only replaces the listener. Run
systemctl is-active ssh.socketfirst if you are unsure which mode the server uses. If it saysinactive, the socket is not in use and a plainsudo systemctl restart sshapplies the change. - 4Test from a second terminal
on your computer, new window ssh -p 2222 you@203.0.113.10Keep the old session open until this works. The first connection on the new port asks you to confirm the host key again: SSH saves keys per host and port, as
[203.0.113.10]:2222. The fingerprint is the same as before, and OpenSSH 8.5 and later say so: the prompt adds “This host key is known by the following other names/addresses” with the entry it already has. scp, sftp and rsync each spell the port option differently; the SSH port guide lists all of them. - 5Close port 22
ufw sudo ufw status numbered sudo ufw delete allow OpenSSH # or: sudo ufw delete allow 22/tcpThe
OpenSSHapplication profile in ufw always means port 22, so it no longer covers your SSH server after the change.
Can I switch Ubuntu back to the classic ssh service?
Yes. If you prefer sshd to run permanently and read its port at every restart, as on Debian, turn socket activation off. These are the commands Ubuntu documents for it; the rm lines remove leftovers from older releases and are harmless if the files do not exist:
sudo systemctl disable --now ssh.socket
sudo rm -f /etc/systemd/system/ssh.service.d/00-socket.conf
sudo rm -f /etc/systemd/system/ssh.socket.d/addresses.conf
sudo systemctl daemon-reload
sudo systemctl enable --now ssh.serviceFrom then on, sudo systemctl restart ssh applies port changes. Ubuntu 22.04 LTS never used socket activation, so the Debian instructions below apply to it unchanged.
How do I change the SSH port on Debian 12 and 13?
Debian runs sshd as an ordinary service, ssh.service, which reads the port when it starts. A stock Debian install has no firewall rules at all; if you added ufw or nftables rules, open the port there first.
sudo ufw allow 2222/tcp # only if ufw is active
echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/port.conf
sudo sshd -t && sudo systemctl restart ssh
ssh -p 2222 you@203.0.113.10 # from a second terminal
sudo ufw delete allow 22/tcp # after the test, if you had a rule for 22How do I change the SSH port on Rocky Linux and CentOS Stream?
Two extra gates. SELinux only lets sshd bind to ports labelled ssh_port_t, and firewalld blocks everything you have not allowed. Forget SELinux and sshd fails to start with Bind to port 2222 on 0.0.0.0 failed: Permission denied, although you are root.
# 1. SELinux: label the port for sshd
sudo dnf install -y policycoreutils-python-utils
sudo semanage port -a -t ssh_port_t -p tcp 2222
sudo semanage port -l | grep ssh_port_t # ssh_port_t tcp 2222, 22
# 2. firewalld
sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
# 3. sshd (the unit is called sshd here)
echo 'Port 2222' | sudo tee /etc/ssh/sshd_config.d/port.conf
sudo sshd -t && sudo systemctl restart sshd
# 4. after testing from a second terminal, close 22
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --reloadIf semanage answers that the port is already defined, another policy owns it: use -m instead of -a to relabel it, or pick a different port.
Why is SSH still listening on port 22 after I changed it?
Five reasons account for nearly every case:
- Ubuntu’s socket was not reloaded.
systemctl restart sshrestarts sshd, but the port belongs tossh.socket. Rundaemon-reload, thenrestart ssh.socket. - Another Port line is still there. For most sshd keywords the first value wins, which is why a drop-in included at the top of
sshd_configoverrides the main file.Portis the exception: everyPortline adds a port. An uncommentedPort 22anywhere keeps 22 open alongside the new one. - A ListenAddress names the port.
ListenAddress 0.0.0.0:22pins that address to 22 whateverPortsays. Remove the:22or change it. - The drop-in is never read. Your file only counts if
sshd_configcontainsInclude /etc/ssh/sshd_config.d/*.conf, which current Debian, Ubuntu and Rocky 9 and 10 do. Ifgrep Include /etc/ssh/sshd_configfinds nothing, setPortinsshd_configitself. - An ssh.socket drop-in pins the port. Guides written for Ubuntu 22.10 to 23.10 set the port with a
ListenStream=line in a file under/etc/systemd/system/ssh.socket.d/, and upgrades from those releases can leave anaddresses.confthere. Such a file overrides or adds to the ports the generator builds fromsshd_config.systemctl cat ssh.socketprints every drop-in; delete the stray one, then rundaemon-reloadandrestart ssh.socket. On Debian, socket activation stays off unless you switched it on, and if you did, such aListenStream=override is the only place the socket’s port is set.
sshd -T prints the configuration sshd would actually use, after all files are merged, which settles the last three in one go:
sudo sshd -T | grep -Ei '^(port|listenaddress)'
# port 2222
# listenaddress [::]:2222
# listenaddress 0.0.0.0:2222With a forgotten Port 22 line still in place, the same command shows both:
port 22
port 2222
listenaddress [::]:22
listenaddress 0.0.0.0:22
listenaddress [::]:2222
listenaddress 0.0.0.0:2222How do I check which port sshd listens on?
sudo ss -tlnp | grep -E ':(22|2222)\b'
# LISTEN 0 4096 0.0.0.0:2222 0.0.0.0:* users:(("sshd",pid=1234,fd=3),("systemd",pid=1,fd=54))
# LISTEN 0 4096 [::]:2222 [::]:* users:(("sshd",pid=1234,fd=4),("systemd",pid=1,fd=55))Grep for the port, not for “sshd”. On Ubuntu 24.04 the socket belongs to systemd until the first connection arrives, so grep ssh can show nothing although everything works. From outside, nc -zv 203.0.113.10 2222 confirms that the firewall lets the port through. Without a second machine at hand, enter the IP and port 2222 in the open port checker, which connects from our server in Amsterdam: Open means the firewall passes it and sshd answers.
How do I connect on the new port?
ssh -p 2222 you@203.0.113.10
scp -P 2222 backup.tar.gz you@203.0.113.10:/tmp/ # capital P for scp
rsync -av -e 'ssh -p 2222' ./site/ you@203.0.113.10:/var/www/site/
ssh-copy-id -p 2222 you@203.0.113.10
git clone ssh://git@203.0.113.10:2222/srv/git/app.gitThe scp command reference covers -P and every other flag, and ssh-copy-id takes -p the same way ssh does when you install a key on the new port.
Typing -p gets old quickly. Put the server in ~/.ssh/config on your computer once, and ssh, scp, rsync and git all pick up the port from the alias:
Host myvps
HostName 203.0.113.10
Port 2222
User you
# then simply
ssh myvps
scp backup.tar.gz myvps:/tmp/In PuTTY, enter the port in the Port field next to the host name on the Session page and save the session. WinSCP and FileZilla have the same field on their login dialog; in FileZilla, choose SFTP as the protocol.
Do I need to tell fail2ban about the new port?
Yes. The default sshd jail uses port = ssh, which means 22. fail2ban would keep detecting failed logins on 2222 and then ban the attackers on a port they are not using. Set the port in jail.local:
[sshd]
enabled = true
# 22,2222 while both ports are open
port = 2222sudo systemctl restart fail2ban
sudo fail2ban-client status sshdKeep comments on lines of their own in jail.local. fail2ban does not treat # after a value as a comment, so port = 2222 # note hands the whole text to the firewall action as the port. Only ; after a space starts an inline comment, as the header of jail.conf notes.
Does a different SSH port make the server more secure?
Only a little. Most drive-by bots only try port 22, so the auth log goes from thousands of failed logins a day to a handful, which makes real problems easier to spot and keeps sshd’s connection slots free. A scanner that checks all ports finds the new one in minutes, though, and a weak password is just as weak on 2222. The protection comes from key-only logins, root login switched off and fail2ban. The SSH hardening guide sets those up; treat the port change as tidying up on top.
Locked out? How do I undo the change from the console?
The error tells you which half went wrong. Connection refused on the new port means sshd is not listening there (see SSH connection refused); Connection timed out usually means a firewall drops it (see SSH connection timed out). Either way, log in through the provider’s console and go back to port 22:
sudo rm /etc/ssh/sshd_config.d/port.conf
# Ubuntu 24.04
sudo systemctl daemon-reload && sudo systemctl restart ssh.socket
# Debian, Ubuntu 22.04
sudo systemctl restart ssh
# Rocky, AlmaLinux, CentOS Stream
sudo systemctl restart sshd
# make sure 22 is allowed again
sudo ufw allow OpenSSH # ufw
sudo firewall-cmd --permanent --add-service=ssh && sudo firewall-cmd --reload # firewalld
# why did it fail? look for "Bind to port ... failed"
sudo journalctl -u ssh -n 30 --no-pager # -u sshd on RockyThat console is what makes the whole exercise safe. Every VMHeaven KVM server has one in the panel, independent of SSH and the firewall, so a wrong port or a forgotten rule is something you fix in a minute rather than a reason to reinstall. On an Ubuntu VPS running 24.04, the five commands at the top of this page are the whole job.
Frequently asked
Why is SSH still listening on port 22 after I changed the port?
On Ubuntu 24.04 the port belongs to systemd's ssh.socket, so restarting the ssh service changes nothing: run 'sudo systemctl daemon-reload' and then 'sudo systemctl restart ssh.socket'. On any distribution, an uncommented 'Port 22' line left in sshd_config or another drop-in keeps 22 open as well, because Port lines add up instead of replacing each other. 'sudo sshd -T | grep -i ^port' shows the ports sshd will really use.
Which port should I choose for SSH?
Any free TCP port that no other service uses or will need, for example 2222 or a free port below 1024 such as 222. Avoid 32768–60999, which Linux uses for outgoing connections, and ports like 3306, 5432, 3389 or 8080. Check that nothing listens on it with 'sudo ss -tlnp | grep :2222'.
Do I need to change fail2ban after changing the SSH port?
Yes. The default sshd jail watches port 22, so its bans would block a port the attackers no longer use. Add 'port = 2222' (or '22,2222' while both are open) to the [sshd] section of /etc/fail2ban/jail.local and restart fail2ban.
How do I undo an SSH port change if I am locked out?
Log in through your provider's web or VNC console, delete the drop-in with 'sudo rm /etc/ssh/sshd_config.d/port.conf' and apply it: 'sudo systemctl daemon-reload && sudo systemctl restart ssh.socket' on Ubuntu 24.04, 'sudo systemctl restart ssh' on Debian, 'sudo systemctl restart sshd' on Rocky. Then make sure the firewall allows port 22 again, for example with 'sudo ufw allow OpenSSH'.