This post summarizes how to change the ssh port on Ubuntu 24.04 LTS or later.
Ubuntu has used systemd socket activation for OpenSSH since Ubuntu 22.10.
Because of this, restarting ssh.service alone may not be enough when changing the ssh port.
On Ubuntu 24.04 LTS or later, the socket configuration can be generated from sshd_config.
So in most cases, I only need to configure Port in sshd_config, reload systemd, and restart ssh.socket.
Background #
On older Ubuntu environments, I usually changed the ssh port by editing /etc/ssh/sshd_config.
# Port 22
Port 22222Then I restarted ssh.
sudo systemctl restart sshHowever, on recent Ubuntu versions, ssh may be managed through systemd socket activation.
In this mode, ssh.socket listens on the ssh port, and ssh.service is started when a connection request comes in.
Therefore, when changing the ssh port, it is important to restart ssh.socket.
Procedure #
Change the ssh port #
Edit /etc/ssh/sshd_config.
sudo vim /etc/ssh/sshd_configFind the Port setting and change it.
# Port 22
Port 22222Reload systemd and restart ssh socket #
Reload systemd.
sudo systemctl daemon-reloadAfter changing sshd_config, I need to reload systemd so that it can regenerate and recognize the updated ssh.socket configuration.
Then restart ssh.socket.
sudo systemctl restart ssh.socketDo not restart only ssh.service.
Configure the firewall #
If UFW is enabled, allow the new ssh port.
sudo ufw allow 22222/tcp
sudo ufw statusConfirmation #
Do not close the current ssh session yet.
Open another terminal and check whether the new port works.
ssh -p 22222 [email protected]After confirming that the new ssh connection works, remove the old port rule if necessary.
sudo ufw delete allow 22/tcpEnd #
That is all.
I forgot that ssh is managed by ssh.socket on recent Ubuntu versions, so I wrote it down as a note.