Change SSH Port on Ubuntu 24.04

In Ubuntu 24.04.2, modifying only the traditional SSH configuration file /etc/ssh/sshd_config often does not work — the port remains on 22.
This is because Ubuntu 24.04.2 manages SSH via systemd socket activation, meaning both configuration files must be updated for changes to take effect.

This guide explains the complete steps to properly change your SSH port.


1. Edit the Main SSH Configuration File

Open the SSH configuration file:

vi /etc/ssh/sshd_config

Find this line:

#Port 22

Uncomment it and change it to your preferred port number:

Port 22312

Save and restart SSH:

systemctl restart ssh

However, the port will likely remain 22, because another service controls the socket.


2. Edit the SSH Socket Configuration

To make the change effective, also edit the socket configuration:

vi /lib/systemd/system/ssh.socket

Find and modify the following lines:

[Socket]
ListenStream=22312
Accept=yes

Reload and restart the socket:

sudo systemctl daemon-reload
sudo systemctl restart ssh.socket

If the new port still doesn’t take effect, proceed with the next step.


3. Stop the Socket and Restart SSH

You’ll need to stop the socket service manually first:

systemctl stop ssh.socket

Then restart SSH normally:

systemctl restart ssh

At this point, SSH should now be listening on port 22312.


4. Verify the New Port

Run the following command:

netstat -anpt | grep 22312

If you see something like this, the port change was successful:

tcp        0      0 0.0.0.0:22312           0.0.0.0:*               LISTEN      1234/sshd: /usr/sbin

5. Firewall and Security Tips

✅ Allow the new port

If you’re using ufw or a cloud firewall, make sure to allow it:

ufw allow 22312/tcp

✅ Keep a backup SSH session

Always keep one SSH session open before restarting the service, in case of configuration errors.

✅ Security best practices

Changing the SSH port (from 22 to 22312) helps reduce bot scans,
but you should also:

  • Disable root password login
  • Use SSH keys for authentication
  • Limit login attempts with fail2ban

✅ Summary

To successfully change SSH port on Ubuntu 24.04.2:

  • Edit both /etc/ssh/sshd_config and /lib/systemd/system/ssh.socket
  • Stop ssh.socket, then restart ssh
  • Confirm new port and firewall rules

Your SSH service is now running securely on port 22312.