How to secure a new Linux VPS in the right order

To secure a VPS, work in this order: update, create a sudo user, limit SSH to keys, close unused ports, turn on automatic patches, add fail2ban, review listening services, then verify. The whole list takes under an hour on Ubuntu 24.04 or Debian 12. The order matters, because most lock-outs come from doing step three before step two.

Updated:

Safety rules that keep you from being locked out

  • Two windows. Keep one SSH session open and untouched. Test every change from a second, new session. An established session survives a restart of the SSH service.
  • A way in without SSH. Open the browser console in the panel once before you begin and confirm that you can log in there with a password. Keys are not used in the console.
  • One change at a time. Change, test, continue. When five things change at once, you cannot tell which one broke access.
  • Keys first. The steps below assume that your key already works. If not, follow connecting with SSH first.

Steps 1 and 2: updates and a normal user

1. Install pending updates

sudo apt update && sudo apt full-upgrade
# is a restart needed?
ls /var/run/reboot-required

If the file exists, restart now, while nothing depends on the server.

2. Create a user with sudo

If your image already gave you a regular user with sudo, skip this step. Otherwise, as root:

apt install sudo
adduser deploy
usermod -aG sudo deploy
install -d -m 700 -o deploy -g deploy /home/deploy/.ssh
install -m 600 -o deploy -g deploy /root/.ssh/authorized_keys /home/deploy/.ssh/authorized_keys

Check the copied file: on some cloud images the root key starts with a command="…" prefix that blocks login. Keep only the part from ssh-ed25519 or ssh-rsa on. Then, in a second window, run ssh deploy@203.0.113.10 followed by sudo -v. Continue only if both work.

Step 3: limit SSH to keys

Put your settings in a separate file. SSH takes the first value it finds, and files are read alphabetically, so a 00- prefix wins over the file that cloud-init may have written.

sudo nano /etc/ssh/sshd_config.d/00-hardening.conf
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
X11Forwarding no
sudo sshd -t && sudo systemctl restart ssh
sudo sshd -T | grep -E '^(permitrootlogin|passwordauthentication|kbdinteractiveauthentication) '

Log in from a new window. Then confirm that passwords are refused; this command must end with "Permission denied (publickey)":

ssh -o PubkeyAuthentication=no deploy@203.0.113.10

Changing the port is optional

Another port cuts log noise and adds no real protection. If you want it, open the new port in ufw (step 4) before switching and add Port 2222 to the file above. The way to apply it differs:

SystemWho holds the portApply with
Ubuntu 24.04ssh.socket (systemd)sudo systemctl daemon-reload && sudo systemctl restart ssh.socket
Debian 12, Ubuntu 22.04the ssh servicesudo systemctl restart ssh

On Ubuntu 24.04 restarting only the service leaves the old port in place. Run sudo ss -tln and look for the new number before you close anything.

Step 4: firewall with a dead man's switch

Ubuntu includes ufw; on Debian run sudo apt install ufw. This sequence schedules an automatic rollback, so a mistake costs ten minutes instead of access:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow OpenSSH        # port 22; for another port: sudo ufw allow 2222/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
# ufw switches itself off after 10 minutes
sudo systemd-run --on-active=10min --unit=ufw-rescue /usr/sbin/ufw disable
sudo ufw enable

Open a new session. If it works, cancel the rollback and check the rules:

sudo systemctl stop ufw-rescue.timer
sudo ufw status verbose

Docker inserts its own rules, so a container published with -p 5432:5432 is reachable despite ufw. Publish it as -p 127.0.0.1:5432:5432 instead; Docker on a VPS says more about this.

Steps 5 and 6: automatic patches and fail2ban

5. Security updates without you

sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
sudo unattended-upgrade --dry-run --debug

Kernel updates take effect only after a restart. If a short night-time reboot is acceptable, create /etc/apt/apt.conf.d/52reboot and check the server clock with timedatectl:

Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:30";

6. Fewer guesses with fail2ban

With passwords disabled, guessing over SSH is hopeless already; fail2ban mainly reduces noise. Debian 12 keeps SSH logs in the journal, hence the systemd backend.

sudo apt install fail2ban python3-systemd
sudo nano /etc/fail2ban/jail.local
[sshd]
enabled  = true
backend  = systemd
# your SSH port
port     = 22
maxretry = 5
findtime = 10m
bantime  = 1h
# your fixed office address
ignoreip = 127.0.0.1/8 198.51.100.7
sudo systemctl restart fail2ban
sudo fail2ban-client status sshd
# remove a ban
sudo fail2ban-client set sshd unbanip 198.51.100.7

Step 7: what is listening?

sudo ss -tulpn
Local addressMeaningAction
127.0.0.1 or [::1]Reachable only from the serverLeave it
0.0.0.0 or [::] on 22, 80, 443Public on purposeKeep it patched
0.0.0.0 on 3306, 5432, 6379, 27017A database exposed to everyoneBind it to 127.0.0.1
A service you do not knowUnused packagesudo systemctl disable --now name

Admin panels and databases do not need a public port at all. Reach them through an SSH tunnel, a company VPN or a private network.

Step 8: verify and repeat monthly

# common ports that are really open, run from your own computer
nmap -Pn 203.0.113.10
# accepted logins
sudo journalctl -u ssh --since "7 days ago" | grep Accepted
# accounts with root rights: only root should appear
awk -F: '$3 == 0 {print $1}' /etc/passwd
getent group sudo
# all key files
sudo find / -xdev -name authorized_keys

Hardening protects the system, not the application. An outdated plugin or a leaked .env file bypasses all eight steps, and only a tested copy stored elsewhere helps after a break-in: see backing up a VPS to S3.

Hardening questions

Does changing the SSH port make a VPS secure?

No. Scanners find the new port sooner or later. It reduces log noise, while keys without passwords are what stops the attacks.

Should I disable root completely?

Disable root login over SSH and use sudo. Keep a root or sudo password for the browser console, because it is your emergency entrance.

Do I need fail2ban if only keys are allowed?

Not strictly. It saves some CPU and log space, and it becomes useful when you add jails for services that do have passwords, such as a web login.

Why is my Docker container open although ufw denies the port?

Docker writes packet-filter rules that are processed before those of ufw. Bind the published port to 127.0.0.1 and put a reverse proxy in front of it.

How often should a VPS be updated?

Security patches daily through unattended-upgrades, everything else once a month, and a restart whenever the reboot-required file appears.

Read next

All VPS pages

This page in other languages: Azərbaycanca · Русский · Türkçe

Servers in Baku, prices in manat

Create an account, top up your balance and order the plan you need.