Security

How to change the default SSH port on a VPS

Your SSH daemon is listening on port 22, and every bot on the internet knows it. Within hours of a fresh VPS being provisioned, you will see thousands of authentication attempts in journalctl -u ssh. Most of them are scripted, hammering common usernames. Moving SSH to a non-standard port does not replace key-based authentication or fail2ban, but it silently removes the overwhelming majority of that noise. On a Debian 12 or Ubuntu 24.04 VPS, the change takes about two minutes and one restart. Here is how to change the default SSH port on a VPS without locking yourself out.

Key takeaways

  • Change the port in /etc/ssh/sshd_config with Port 2222, then systemctl restart ssh.
  • Open the new port in your firewall before you restart SSH, and keep the old one open until you have verified the new listener works.
  • If SELinux is enforcing, run semanage port -a -t ssh_port_t -p tcp 2222 or SSH will silently refuse the connection.
  • Keep a second terminal session open while you test, so a typo never strands you without access.

Prerequisites

  • A Linux VPS running Ubuntu 24.04 LTS, Debian 12, or AlmaLinux 9 / Rocky Linux 9.
  • Root access, or a user with full sudo privileges.
  • An SSH key pair already configured. If you still rely on password authentication, set up keys first; changing the port is not what protects you.
  • Access to your VPS provider's control panel, preferably with a browser-based console, as a recovery path in case you restart SSH before the firewall rule is in place.

Why move SSH off port 22 at all

Port 22 is scanned continuously. A server on a public IPv4 address, even a quiet one, collects login attempts from the moment the OS boots. The scans are not targeted at you. Attackers sweep entire IP ranges and try a handful of common passwords against root and a few weak usernames.

Moving SSH to a random high port, say 2222 or 40222, takes your daemon out of that sweep. The scanners check 22, run a few more common ports, and move on. You still need key-based authentication, a strong passphrase, and something like fail2ban or CrowdSec for the traffic that does find you. Changing the port is one layer, not the whole defense. It does, however, cut the log noise dramatically, which makes real intrusion attempts far easier to spot.

Step 1 - Pick a port and edit sshd_config

Choose a port above 1024 so the SSH daemon does not need to bind as root. I use 2222 in this guide, but anything consistent works. Avoid ports already in use by other services; check with ss -tlnp first.

Edit the SSH daemon configuration:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sudo nano /etc/ssh/sshd_config

Find the line that reads #Port 22 and change it to:

Port 2222

Keep the old port open for now. You can add a second Port line to listen on both during the transition, but on a production server I prefer a single clean change with the firewall updated first. The commented-out line means SSH is currently on the default, so adding the uncommented directive is enough.

Validate the configuration before restarting:

sudo sshd -t

No output means the syntax is valid. If it prints an error, fix it before proceeding.

Step 2 - Open the new port in the firewall

This is where most lockouts happen. You restart SSH, the new port is blocked, and the old one no longer accepts connections. On Ubuntu and Debian, the default is UFW. On AlmaLinux and Rocky, it is firewalld. Do this before restarting SSH.

For UFW:

sudo ufw allow 2222/tcp
sudo ufw status

For firewalld:

sudo firewall-cmd --permanent --add-port=2222/tcp
sudo firewall-cmd --reload
sudo firewall-cmd --list-ports

If you use your provider's cloud firewall instead of, or in addition to, the OS firewall, add the rule there too. On a Linux VPS managed through a control panel, both layers are common; you need the rule in whichever one actually filters the traffic.

Do not remove the allow rule for the old port yet. Keep it until you have verified the new listener and connected through it.

Step 3 - Handle SELinux if you run AlmaLinux or Rocky

On AlmaLinux 9 or Rocky Linux 9, SELinux runs enforcing by default and will block the new port even if the firewall allows it. Skip this step on Ubuntu or Debian, which do not ship SELinux.

Check whether SELinux is enforcing:

getenforce

If it prints Enforcing, add the port to the SSH SELinux type:

sudo semanage port -a -t ssh_port_t -p tcp 2222

If semanage is not installed, install it with sudo dnf install policycoreutils-python-utils. Verify the mapping:

sudo semanage port -l | grep ssh

You should see both 22 and 2222 under ssh_port_t. Without this step, SSH restarts, the port appears open in the firewall, and connections silently time out. This exact failure sends a lot of people to their provider's emergency console.

Step 4 - Restart SSH and verify the new port

Keep your current session open. Open a second terminal and connect to the new port before you consider the job done. Restart the daemon:

sudo systemctl restart ssh

On AlmaLinux and Rocky the service name is sshd rather than ssh. Check the listener:

ss -tlnp | grep ssh

You should see 0.0.0.0:2222 and [::]:2222 in the output. Then, from your local machine, connect to the new port:

ssh -p 2222 user@your-server-ip

If the connection succeeds, close the old port and remove any remaining Port 22 directive from the config. On a VPS used for SMTP or any other service, also make sure the monitoring and backup scripts that connect over SSH use the new port; a cron job silently failing after a port change is a classic oversight.

Step 5 - Update SSH clients and automation

Any tool that connects to this server over SSH needs the new port. That includes your local ~/.ssh/config, deployment scripts, CI/CD runners, and monitoring agents. For the local config:

Host myserver
    HostName your-server-ip
    User root
    Port 2222

Ansible inventory, rsync over SSH, and git push over SSH all accept a port parameter. Set it once and test each one. A deployment pipeline that hardcoded the default port will fail silently at the next release. Running n8n on a VPS or other automation platforms that trigger shell commands over SSH means checking the webhook or node configuration that connects back to the server.

Why keep key-based authentication and a second factor

Changing the SSH port is not a substitute for proper authentication. A determined attacker who finds the port still only needs a valid credential. Disable password authentication once your keys are confirmed working:

PasswordAuthentication no
PermitRootLogin prohibit-password

This forces key-based authentication and allows root only with a key, never a password. Add these to sshd_config, run sudo sshd -t, and restart SSH. Combine this with fail2ban or CrowdSec and you have a realistic hardening baseline. The port change, the key requirement, and the ban tool each cover a different gap; relying on any one of them alone leaves obvious holes.

Troubleshooting common lockout scenarios

Even with care, things go wrong. Here are the failures I see most often, and the fix for each.

Connection times out after restart. The firewall is blocking the new port. Use your provider's browser console to log in, then run sudo ufw allow 2222/tcp or the firewalld equivalent. This is why the emergency console matters; keep it bookmarked.

Connection refused, but the firewall is open. Check ss -tlnp | grep ssh. If SSH is listening on 22 only, the config change did not apply. Re-read sshd_config for typos and make sure Port 2222 is not commented out.

SELinux is blocking the port on AlmaLinux. The firewall shows the port open, but connections hang. Run sudo semanage port -a -t ssh_port_t -p tcp 2222 and retry. Put SELinux in permissive mode temporarily to confirm the cause: sudo setenforce 0, test, then re-enforce after the fix.

FAQ

What is the best port to change SSH to?

Any unused port above 1024 works. I typically use 2222 for simplicity or a random port in the 40000-50000 range for obscurity. Avoid ports assigned to common services like 80, 443, or 8080 to prevent conflicts.

Does changing the SSH port improve security?

Yes, but only against automated scans. It reduces brute-force attempts dramatically, yet a targeted attacker will find the port. Real security comes from key-based authentication, fail2ban, and disabling root password login.

Can I keep SSH on both port 22 and the new port?

Yes. Add two Port lines in sshd_config to listen on both during migration. Remove the old line once you have verified everything works. This is a useful transition strategy for production servers.

What happens if I restart SSH and cannot connect?

Use your VPS provider's browser-based console to log in locally. Revert the config from the backup you created, or open the new port in the firewall. Always keep a second session open while testing to avoid this situation entirely.

Related articles

修改 VPS 默认 SSH 端口步骤

将 VPS 的 SSH 从默认端口 22 移到如 2222 的高位端口,可大幅减少自动化暴力破解尝试。操作前先备份 sshd_config,再通过 ufw 或 firewalld 开放新端口,AlmaLinux 用户还需执行 semanage 配置 SELinux。务必保留一个终端会话,重启 SSH 后用新端口验证连接,确认无误再关闭旧端口。此操作需配合密钥认证和 fail2ban,才能构成完整的安全基线。

Note: This guide is for general reference. Every system and infrastructure has its own specifics, so test each step in a safe environment and consult a qualified engineer before applying it in production.