Skip to main content

Changing the SSH Port on Ubuntu 24.04 LTS or Later

··2 mins·
Makoto Morinaga
Author
Makoto Morinaga
A personal notebook for tech notes, coding, and system experiments.
Table of Contents

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.

conf
# Port 22
Port 22222

Then I restarted ssh.

shell
sudo systemctl restart ssh

However, 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.

shell
sudo vim /etc/ssh/sshd_config

Find the Port setting and change it.

conf
# Port 22
Port 22222

Reload systemd and restart ssh socket
#

Reload systemd.

shell
sudo systemctl daemon-reload

After changing sshd_config, I need to reload systemd so that it can regenerate and recognize the updated ssh.socket configuration.

Then restart ssh.socket.

shell
sudo systemctl restart ssh.socket

Do not restart only ssh.service.

Configure the firewall
#

If UFW is enabled, allow the new ssh port.

shell
sudo ufw allow 22222/tcp
sudo ufw status

Confirmation
#

Do not close the current ssh session yet.

Open another terminal and check whether the new port works.

shell
ssh -p 22222 [email protected]

After confirming that the new ssh connection works, remove the old port rule if necessary.

shell
sudo ufw delete allow 22/tcp

End
#

That is all.

I forgot that ssh is managed by ssh.socket on recent Ubuntu versions, so I wrote it down as a note.

Related