Skip to content

How to Secure and Harden a VPS from Scratch

A complete guide to hardening a VPS: SSH keys and disabling root and password login, changing the port, a non-root user with limited privileges, the UFW firewall, Fail2ban against brute force, automatic security updates, reducing the attack surface, logs and monitoring, backups and securing services, with commands, tables and a checklist.

VPSيوسف الحربي35 min read
Illustration of a server cube inside concentric defensive rings with a padlock, a wall and a key, representing hardening a VPS
On this page

Why VPS hardening is not optional but a necessity

The moment your server is connected to the internet with a public IP address, it becomes a target. This is not scaremongering but a measurable reality: put a new server on the internet with SSH open on port 22 and watch its logs after a single hour. You will find dozens or even hundreds of login attempts from IP addresses around the world, trying common usernames (root, admin, user) and passwords from leaked lists. These are not attacks aimed at you personally but bots that scan the entire internet automatically, looking for any server with a weak default configuration to break into.

The difference between shared hosting and a VPS is fundamental here. On shared hosting, the provider takes care of securing the server and you are isolated in your account. On an unmanaged VPS, you are solely responsible for security from layer zero. The server reaches you with a raw operating system and a root password, and everything after that (hardening, updates, monitoring) is up to you. This power is itself the source of the risk: a server left at its default configuration without hardening is an open invitation.

The consequences are not theoretical. A compromised server may be used to send spam, getting your IP blocklisted; turned into a node in a DDoS botnet; used to mine cryptocurrency, with the miner devouring its CPU and your bill; or, worst of all, your customers' data and your databases may be stolen. More dangerous still, a breach is often silent: the attacker does not want you to discover it, but to stay as long as possible.

The philosophy: defense in depth

The principle that governs this whole guide is defense in depth: do not rely on a single layer of protection, but build several independent layers so that if an attacker breaks through one, the next stops them. If you relied only on a strong password, leaking it would mean everything collapses. But if login is by SSH key (not a password), on a non-standard port, behind a firewall that rejects every port except the allowed ones, with Fail2ban banning repeated attempts and a user with limited privileges who does not have root, then breaking through a single layer is not nearly enough.

VPS hardening layersMonitoring and alerts + log analysisRegular off-site backupsAutomatic security updatesFail2ban: banning guessing attemptsUFW firewall (necessary ports only)Key-based SSH: root and password login disabledVPS (the core)Harden layer by layer: each one closes a different gap
Hardening a VPS layer by layer: key-based SSH with root disabled, the UFW firewall, Fail2ban, automatic updates, off-site backups, and monitoring and alerts, around the server's core.

Each layer in this diagram is independent of the others, and each adds a new obstacle for the attacker. The layers from the outside in: access control (SSH keys and disabling root), the firewall (UFW), intrusion detection and blocking (Fail2ban), attack surface reduction (stopping services), self-protection (automatic updates), and finally visibility and recovery (monitoring and backups). We will build these layers one by one.

Overview of the hardening map (an initial checklist)

Before diving into the commands, here is the complete roadmap in a single table. This is the checklist we will apply step by step, ordered by priority:

#Hardening actionLayerPriorityRisk if neglected
1Create a non-root user with sudo privilegesAccess controlCriticalRunning everything as root
2Set up SSH keys for authenticationAccess controlCriticalRelying on a guessable password
3Disable root login over SSHAccess controlCriticalRoot targeted directly
4Disable password authenticationAccess controlCriticalBrute-force attacks
5Change the SSH port (optional)Access controlMediumAutomated scanning noise
6Restrict users with AllowUsersAccess controlHighLogins to unintended accounts
7Enable the UFW firewallFirewallCriticalAll ports exposed
8Install and configure Fail2banIntrusion detectionHighUnlimited guessing
9Enable automatic security updatesSelf-protectionCriticalKnown vulnerabilities left unpatched
10Stop unnecessary servicesAttack surface reductionHighPorts open for no reason
11Secure databases and servicesAttack surface reductionHighA database exposed to the world
12Set permissions on sensitive filesAttack surface reductionHighUnauthorized reading/modification
13Set up logging and monitoringVisibilityMediumA silent, undetected breach
14Set up off-site backupsRecoveryCriticalPermanent data loss

If you are starting from a completely empty server and have not done the basic setup yet (first connection, system update), start with the guide to setting up your first VPS from scratch, then come back here for the advanced hardening layers. And if you are not yet comfortable with the basics of connecting, the article on SSH basics is the right starting point.

Layer 1: a non-root user and the principle of least privilege

The first mistake beginners make is living inside the root account. The root user is the absolute god of a Linux system: it can delete any file, change any setting, and install or remove anything without restriction. Doing your daily work as root means that any typo could destroy the system, and that any compromised program immediately gains full control. The solution is the principle of least privilege: always work with the least privileges your task requires, and elevate privileges temporarily only when needed, through sudo.

Creating a user with sudo privileges

Connect to the server as root the first time, then create a new user (we will call it deploy as an example) and add it to the sudo group:

bash
# Create the new user (you will be asked for a password and optional details)
adduser deploy

# Add the user to the sudo group (on Ubuntu/Debian)
usermod -aG sudo deploy

# On AlmaLinux/CentOS, use the wheel group instead of sudo:
# usermod -aG wheel deploy

# Check that the user is in the right group
groups deploy

You now have a deploy user that can run administrative commands by typing sudo before them (and will be asked for its password to confirm). Remember: do not move on to disabling root login until you are completely sure the deploy user works and can log in and get sudo; otherwise you may lock yourself out of the server.

The principle of least privilege in practice

Wrong practiceSafe alternativeReason
Daily work as rootA regular user + sudo when neededLimits the impact of mistakes and breaches
sudo su - to stay as root for longsudo <command> for each commandAn open root session is a permanent risk
Running web apps as rootA dedicated service user (www-data)Isolates the app from the system
Passwordless sudo for everyonesudo with a password, limited to those who need itPrevents automatic escalation

Layer 2: SSH keys instead of a password

The most important security decision you will ever make is giving up the SSH password and replacing it with cryptographic keys. A password, however long, can be guessed, can be stolen by phishing, and is tried automatically millions of times. An SSH key, on the other hand, is a huge mathematical pair (usually 256 bits for Ed25519): a private key that stays on your computer and never leaves it, and a public key placed on the server. The private key cannot be derived from the public one, and it cannot be guessed in practice.

How does SSH key authentication work?Your computer (client)Private keyThe serverauthorized_keys (public)1 · Connection request (names the key)2 · Challenge encrypted with the public key3 · Answered with the private key as proof4 · Match ⇒ login without a password
Key authentication in SSH: your computer keeps the private key and the server the public key; an encrypted challenge answered with the private key ⇒ secure login without a password.

As the diagram shows, when you connect, the server asks you to prove that you hold the private key without actually revealing it (by signing a mathematical challenge). This kind of authentication is almost completely immune to guessing.

Generating the key pair on your computer

Run this on your local computer (not on the server). We recommend the modern Ed25519 algorithm, which is fast and more secure:

bash
# Generate an Ed25519 key pair (the best choice today)
ssh-keygen -t ed25519 -C "deploy@my-vps" -f ~/.ssh/id_ed25519

# An alternative compatible with very old systems (4096-bit RSA)
# ssh-keygen -t rsa -b 4096 -C "deploy@my-vps"

You will be asked to enter a passphrase for the private key: enter a strong one. This is an extra layer of security: even if the private key file is stolen, the attacker is still helpless without the passphrase. You will get two files: id_ed25519 (the private key: guard it with your life and never share it) and id_ed25519.pub (the public key: this is the one copied to the server).

Copying the public key to the server

bash
# The easiest way: ssh-copy-id copies the public key to the user on the server
ssh-copy-id -i ~/.ssh/id_ed25519.pub deploy@203.0.113.10

# If ssh-copy-id is not available, copy it manually:
cat ~/.ssh/id_ed25519.pub | ssh deploy@203.0.113.10 \
  "mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

Now try logging in: ssh deploy@203.0.113.10. You should get in without being asked for the server account's password (you may be asked for the key's passphrase if you set one). Do not take a single step further until you are sure key login works, because the next step disables the password for good. For more detail on generating and managing keys, see SSH basics.

Layer 3: hardening the sshd configuration

Now we come to the heart of hardening: the SSH service's configuration file on the server, located at /etc/ssh/sshd_config. This is where we disable everything that opens the door to attackers. Open the file in an editor (do this from the deploy session with sudo):

bash
sudo nano /etc/ssh/sshd_config

Edit (or add) the following values. The most important: PermitRootLogin no, PasswordAuthentication no, and setting the port and the allowed users:

bash
# A non-standard port reduces automated scanning noise (optional but useful)
Port 2222

# Block direct root login: log in as a regular user, then sudo
PermitRootLogin no

# Disable password authentication completely: keys only
PasswordAuthentication no
ChallengeResponseAuthentication no
KbdInteractiveAuthentication no

# Enable public key authentication explicitly
PubkeyAuthentication yes

# Block empty passwords and limit attempts and sessions
PermitEmptyPasswords no
MaxAuthTries 3
MaxSessions 5
LoginGraceTime 30

# Restrict login to specific users only
AllowUsers deploy

# Disable X11 forwarding if you do not need it
X11Forwarding no

After saving, test that the configuration is valid before restarting to avoid breaking the service:

bash
# Check the file's syntax for errors before applying it
sudo sshd -t

# If no error appears, restart the SSH service
sudo systemctl restart ssh

# On some systems the service name may be sshd:
# sudo systemctl restart sshd

Critical: before you close your current session, open a new SSH session in a separate window and make sure you can log in with the new port and user (ssh -p 2222 deploy@203.0.113.10). If it works, close the old one safely. If it fails, your old session is still open so you can fix the mistake. This rule saves you from the "I locked myself out of the server" scenario.

SettingRecommended valueDefaultWhat it does
Port2222 (or any port other than 22)22Reduces automated scanning of the well-known port
PermitRootLoginnoprohibit-passwordPrevents root from being targeted directly
PasswordAuthenticationnoyesEliminates password-guessing attacks
PubkeyAuthenticationyesyesEnables key-based authentication
PermitEmptyPasswordsnonoBlocks accounts without a password
MaxAuthTries36Limits authentication attempts per connection
LoginGraceTime30120Shortens the time allowed to complete login
AllowUsersdeploy(all)Restricts login to specific users
X11Forwardingnoyes/noDisables graphical interface forwarding
ChallengeResponseAuthenticationnoVariesCloses alternative authentication paths

An important note: if you change the port, you will need to open the new port in the UFW firewall before restarting SSH (the next step); otherwise UFW will block your new connection. The safe order: open the port in UFW first, then change the port in sshd, then restart.

Layer 4: the UFW firewall

The firewall is the guard at the server's gate: it decides which network traffic is allowed and which is rejected. The golden principle is a default deny policy: reject all incoming connections, then open only the ports you actually need, rather than opening everything and trying to plug the holes later. UFW (short for Uncomplicated Firewall) makes this easy on Ubuntu/Debian.

bash
# Install UFW if it is not already present
sudo apt update && sudo apt install -y ufw

# The most important step: deny all incoming, allow all outgoing
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow the SSH port, if you are on the default port:
sudo ufw allow OpenSSH

# If you changed the SSH port to 2222, allow it explicitly instead of the previous line:
sudo ufw allow 2222/tcp

# Allow web traffic (HTTP and HTTPS) if you host a site
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable the firewall (it warns it may cut SSH; make sure you allowed your port first)
sudo ufw enable

# Check the status and the active rules
sudo ufw status verbose

A critical warning: before running ufw enable, be 100% sure you have allowed the correct SSH port (whether OpenSSH or 2222). If you enable the firewall with a deny policy without allowing the SSH port, your session will be cut immediately and you will only be able to get back in through the console in your provider's control panel.

Common ports in UFW

ServicePortProtocolUFW commandWhen to open it
SSH (default)22TCPufw allow OpenSSHFor remote administration
SSH (custom)2222TCPufw allow 2222/tcpWhen you change the port
HTTP80TCPufw allow 80/tcpFor websites (and HTTPS redirects)
HTTPS443TCPufw allow 443/tcpFor SSL-encrypted sites
MySQL/MariaDB3306TCPNever open it to the worldLocal only (see below)
PostgreSQL5432TCPNever open it to the worldLocal only
Redis6379TCPNever open it to the worldLocal only
FTP21TCPAvoid it (use SFTP)Unencrypted: dangerous

Note the golden rule in the table: database and Redis ports are never opened to the world. These services should listen on 127.0.0.1 only, so they do not need a UFW rule at all; we will cover this in the section on securing services.

Restricting ports to a specific source

For more hardening, you can restrict the SSH port to your own IP address only (if you have a static IP):

bash
# Allow SSH only from a specific IP address (replace it with yours)
sudo ufw allow from 198.51.100.25 to any port 2222 proto tcp

# To delete an old rule by number: list the numbered rules, then delete
sudo ufw status numbered
sudo ufw delete 3

Layer 5: Fail2ban against brute-force attacks

Even after disabling the password, bots will keep knocking on the SSH port. This is where Fail2ban comes in: a tool that monitors the server's logs and, when it detects a number of failed attempts from a single IP address within a short period, automatically bans that address through the firewall for a set time. This turns guessing from unlimited attempts into a handful before the ban.

bash
# Install Fail2ban
sudo apt update && sudo apt install -y fail2ban

# Do not edit jail.conf directly: create jail.local so it survives updates
sudo nano /etc/fail2ban/jail.local

Put the following content in jail.local. It sets the general rules and then enables SSH protection (note that the port matches your custom port):

bash
[DEFAULT]
# Ban duration (in seconds): one hour here
bantime  = 3600
# Window for counting attempts (in seconds): 10 minutes
findtime = 600
# Number of failed attempts before a ban
maxretry = 3
# Do not ban your trusted addresses (add your computer's IP and localhost)
ignoreip = 127.0.0.1/8 ::1 198.51.100.25

[sshd]
enabled = true
port    = 2222
# On modern Ubuntu it reads from the systemd journal
backend = systemd
maxretry = 3
bantime  = 3600

Start the service and check its status:

bash
# Enable Fail2ban and start it at boot
sudo systemctl enable --now fail2ban

# Check the overall service status
sudo fail2ban-client status

# Check the sshd jail specifically (banned IPs, attempt count)
sudo fail2ban-client status sshd

Useful Fail2ban commands

TaskCommandNote
Status of all jailssudo fail2ban-client statusShows the active jails
Status of a specific jailsudo fail2ban-client status sshdShows the banned IPs
Ban an IP manuallysudo fail2ban-client set sshd banip 203.0.113.7Immediate ban
Unban an IPsudo fail2ban-client set sshd unbanip 203.0.113.7When banned by mistake
Reload the configurationsudo fail2ban-client reloadAfter editing jail.local
Test the regular expressionsudo fail2ban-regex /var/log/auth.log <filter>For diagnosing filters

An important tip: add your computer's IP address to ignoreip to avoid banning yourself by mistake if you get the login wrong several times. If you do lock yourself out, you will need to log in through the provider's console and lift the ban with unbanip.

Layer 6: automatic security updates

The biggest source of server compromises is known, unpatched vulnerabilities. When a vulnerability is discovered in a package, the fix is released quickly, but if you do not install it, you stay exposed. The solution: automatic security updates through the unattended-upgrades package, which installs security patches without manual intervention.

bash
# Install the tool and the priority configuration package
sudo apt update
sudo apt install -y unattended-upgrades apt-listchanges

# Enable automatic updates (when prompted, choose Yes)
sudo dpkg-reconfigure -plow unattended-upgrades

# Adjust the details in the configuration file
sudo nano /etc/apt/apt.conf.d/50unattended-upgrades

In the 50unattended-upgrades file, make sure the security updates source is enabled, and enable automatic removal of unused packages and rebooting when necessary (at a quiet time):

bash
Unattended-Upgrade::Allowed-Origins {
    "${distro_id}:${distro_codename}-security";
    "${distro_id}ESMApps:${distro_codename}-apps-security";
};

// Automatically remove unused dependencies
Unattended-Upgrade::Remove-Unused-Dependencies "true";

// Reboot automatically if a kernel update requires it, at a quiet time
Unattended-Upgrade::Automatic-Reboot "true";
Unattended-Upgrade::Automatic-Reboot-Time "04:00";

Enable the periodic schedule in the 20auto-upgrades file:

bash
sudo nano /etc/apt/apt.conf.d/20auto-upgrades
bash
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";

Test that everything works without actually applying anything:

bash
# A dry run that shows what would be updated without installing
sudo unattended-upgrade --dry-run --debug

Automatic update options

OptionValueEffect
Allowed-Origins-securityInstalls security patches only (the safest)
Automatic-ReboottrueReboots when the kernel is updated
Automatic-Reboot-Time04:00Schedules the reboot for a quiet time
Remove-Unused-DependenciestrueCleans up orphaned packages automatically
Unattended-Upgrade (periodic)1Enables the daily job

A tip: limit automatic updates to security patches only, and leave major feature upgrades to be applied manually after testing, so that an update does not break your application unsupervised.

Layer 7: reducing the attack surface

Every running service and every open port is a potential door for an attack. Reducing the attack surface means shutting down everything you do not actually need: stop unnecessary services, close unused ports and remove superfluous packages. The rule: what is not running cannot be hacked.

Finding out what is listening on the network

First, find out what is actually listening on the ports:

bash
# List all listening ports with their programs (the modern ss tool)
sudo ss -tulpn

# An older alternative for those who prefer netstat
# sudo netstat -tulpn

# To scan the ports from outside (from another machine) with nmap
nmap -sV 203.0.113.10

Look in the output for any service listening on 0.0.0.0 (all interfaces) that you do not recognize or do not need. Every line is an exposed port that you must either justify or close.

Stopping and removing unnecessary services

bash
# List all services enabled at boot
sudo systemctl list-unit-files --type=service --state=enabled

# Stop a service and prevent it from starting at boot (example: a service you do not need)
sudo systemctl disable --now avahi-daemon

# Remove an unnecessary package completely (common example: a default mail server)
sudo apt purge -y exim4 exim4-base
sudo apt autoremove -y

Examples of services that are often present without being needed: avahi-daemon (local network discovery), cups (printing), rpcbind, and default mail servers such as exim4 on a server that does not send email. Check each service before stopping it.

Securing services: make them listen locally

The most dangerous misconfiguration is leaving a database listening on all interfaces (0.0.0.0), so it is exposed to the internet. The right approach is to have it listen on 127.0.0.1 only, so your local application can reach it and no one from outside can.

bash
# MySQL/MariaDB: in /etc/mysql/mariadb.conf.d/50-server.cnf make sure of:
# bind-address = 127.0.0.1

# PostgreSQL: in postgresql.conf make sure of:
# listen_addresses = 'localhost'

# Redis: in /etc/redis/redis.conf make sure of:
# bind 127.0.0.1 ::1
# protected-mode yes

# After editing, restart the service and check it is no longer on 0.0.0.0
sudo systemctl restart mariadb
sudo ss -tulpn | grep 3306

The Nginx web server should be hardened by hiding its version, preventing script execution in upload folders and adding security headers:

bash
# In /etc/nginx/nginx.conf, inside http {}, hide the Nginx version
# server_tokens off;

# Test the configuration, then reload
sudo nginx -t && sudo systemctl reload nginx

To go deeper into Nginx and security headers (CSP, HSTS, X-Frame-Options), see the guide to HTTP security headers, which explains each header and how to set it.

Permissions on sensitive files

Wrong permissions on sensitive files allow users who should not reach them to read or modify them. Set them precisely:

bash
# The user's SSH folder: 700 (owner only)
chmod 700 ~/.ssh

# The authorized keys file: 600
chmod 600 ~/.ssh/authorized_keys

# The private key (if present on the server): 600
chmod 600 ~/.ssh/id_ed25519

# The global SSH configuration file, owned by root, with 644
sudo chown root:root /etc/ssh/sshd_config
sudo chmod 644 /etc/ssh/sshd_config

# Configuration files containing passwords (such as wp-config.php): 640, owned by the web user
sudo chown www-data:www-data /var/www/html/wp-config.php
sudo chmod 640 /var/www/html/wp-config.php

Permissions for sensitive files

File/folderPermissionsOwnerReason
~/.ssh700The userPrevents others from seeing the keys
~/.ssh/authorized_keys600The userRead/write for the owner only
~/.ssh/id_ed25519 (private)600The userProtects the private key
~/.ssh/id_ed25519.pub (public)644The userPublic but not modifiable
/etc/ssh/sshd_config644rootSystem configuration protected from modification
wp-config.php640www-dataHides the database credentials
Web folders755www-dataExecute/read with no world write
Web files644www-dataRead without execute

Layer 8: logs, monitoring and alerts

Hardening is not complete without visibility: the ability to know what is happening on your server and to detect anomalies early. The worst breach is the silent one you do not notice for months. Logs are your eyes on the server.

bash
# Monitor failed and successful login attempts (Ubuntu/Debian)
sudo journalctl -u ssh --since "today"
# Or the file directly on some systems:
sudo tail -f /var/log/auth.log

# Recent successful logins
last -a | head -20

# Failed login attempts
sudo lastb | head -20

# Monitor resource usage in real time (to detect hidden mining)
top
# Or, better
htop

Monitoring indicators

IndicatorCommand/sourceDanger sign
Failed SSH attempts/var/log/auth.log, lastbA sudden spike from a single IP
CPU usagehtop, topAn unknown process using 100%
Open network connectionsss -tunpOutgoing connections to strange addresses
Disk spacedf -hSudden filling up (may be an attack log)
Unknown processesps auxPrograms you do not recognize
Changes to system filesAIDE/TripwireA sensitive file's fingerprint has changed
New loginslastLogins at unusual times

For advanced monitoring, consider installing a file integrity checker such as AIDE, which takes a "fingerprint" of system files and alerts you to any unexpected change, and a rootkit scanner such as rkhunter:

bash
# Scan for rootkits periodically
sudo apt install -y rkhunter
sudo rkhunter --update
sudo rkhunter --check --skip-keypress

Layer 9: off-site backups

All the hardening above reduces the likelihood of disaster, but it does not eliminate it. Backups are the last safety net: if the server is compromised, its data is encrypted by ransomware, or there is a hardware failure, the off-site backup is what brings you back to life. The golden rule is 3-2-1: three copies of the data, on two different media, one of them off-site.

Three layers of safe backupsSnapshotOff-siteApplicationInfra snapshotFull off-site copyApp backupFast restoreof the whole serverProtects againstserver failureFiles + databasekept separately
Three layers of protection: a quick snapshot, a full off-site copy, and an application/database-level backup.

Most importantly: the backup must be off the server itself. A copy on the same disk does not help you if the server is compromised or the hardware fails. Send it to object storage (such as Cloudflare R2 or S3) or to another server:

bash
# Example: archive the site's database and files, then upload them to external storage
# 1) Back up the database
mysqldump -u root -p --all-databases | gzip > /tmp/db-$(date +%F).sql.gz

# 2) Archive the site's files
tar czf /tmp/www-$(date +%F).tar.gz /var/www

# 3) Sync securely to an external server/storage with rsync over SSH
rsync -avz -e "ssh -p 2222" /tmp/db-*.sql.gz /tmp/www-*.tar.gz \
  backup@backup-server:/backups/

# 4) Schedule the backup daily with cron
crontab -e
# Add the following line to run daily at 3 a.m.:
# 0 3 * * * /home/deploy/scripts/backup.sh

Test restores regularly. A backup whose restore has never been tested is not a backup but a hope. Set a monthly appointment to restore a backup on a test server and confirm it is complete and intact. To dig deeper into backup strategies and scheduling, see the backup guide.

Backup layers

TypeFrequencyLocationUse
Provider snapshotDaily/weeklyProvider's control panelFast recovery of the whole system
Database backupDailyExternal storageRestoring critical data
Files backupDaily/weeklyExternal storageRestoring content and settings
Full off-site copyWeeklyAnother geographic regionMajor disasters

2FA for SSH (an extra layer)

For a higher level of security, you can add two-factor authentication (2FA) to SSH through Google Authenticator, so that, in addition to the key, a time-based code (TOTP) from an app on your phone is required. This combines "something you have" (the key) with a second "something you have" (the phone) in an independent layer:

bash
# Install the PAM module for TOTP
sudo apt install -y libpam-google-authenticator

# Run the setup for each user (generates a QR code and emergency codes)
google-authenticator

Enabling it requires editing /etc/pam.d/sshd and setting AuthenticationMethods publickey,keyboard-interactive in sshd_config. Be careful and always test in a new session before closing the current one, because this step is delicate and can lock you out if it is misconfigured.

Expert tips for after the basic hardening

  • Review your logs weekly: set aside 10 minutes to review lastb and auth.log. Anomalous patterns show up early for anyone who looks.
  • Use a password manager for key passphrases and service accounts. Never reuse them.
  • Separate environments: do not share one server between production and testing. A breach of the test environment must not reach production.
  • Least privilege for applications: run each application as a dedicated service user with limited privileges, not as root and not as your admin user.
  • Document your configuration: keep a record (off the server) of what you changed and why, to make recovery and rebuilding easier.
  • Enable automatic alerts: set up an email notification for every successful SSH login, so you know immediately about any unexpected login.
  • Harden the control panel if there is one: if you run cPanel or another panel, it has its own attack surface; see securing cPanel.
  • Also update manually on a regular basis: automatic updates cover security, but review major upgrades manually each month, after a backup.

Troubleshooting

Most of the problems you will face during hardening involve locking yourself out of the server. This table covers the common symptoms, their causes and their fixes:

SymptomPossible causeFix
Permission denied (publickey) after disabling the passwordThe public key was not copied correctly, or the .ssh permissions are wrongLog in through the provider's console and check authorized_keys and its permissions (600) and the .ssh folder (700)
Connection refused after changing the portYou are connecting on the old port, or UFW is blocking the new oneConnect with -p 2222 and make sure of ufw allow 2222/tcp
Connection timed out after enabling UFWThe port is not allowed in the firewall, or the provider's firewall blocks itOpen the port in UFW and in the Cloud Firewall in the provider's panel
I locked myself out after ufw enableYou enabled deny without allowing SSHLog in through the provider's console and run ufw allow 2222/tcp
Fail2ban banned my IPYou exceeded maxretry, or your IP is not listed in ignoreipVia the console: fail2ban-client set sshd unbanip <ip> and add it to ignoreip
sudo: command not found for the new userThe user is not in the sudo/wheel groupAs root: usermod -aG sudo deploy
The site does not open after enabling UFWPort 80/443 is not allowedufw allow 80/tcp and ufw allow 443/tcp
The app cannot reach the database after binding locallyThe app connects via an external IP, not localhostSet the app's connection to 127.0.0.1
sshd -t shows a syntax errorA typo in sshd_configFix the indicated line and do not restart until sshd -t passes

If you lock yourself out of SSH completely

Your most important safety net is the emergency console (Console/VNC) in the provider's control panel. Every serious VPS provider offers browser-based access to the server that does not go through SSH or the firewall at all. Through it you can log in as root (or with the user's password) and fix any mistake in sshd_config, UFW or Fail2ban. That is why we repeat it throughout the guide: do not close your old session until you have confirmed the new one works, and know how to reach your provider's console before you need it.

Frequently asked questions

Does changing the SSH port really harden the server? Changing the port greatly reduces the noise of automated scans targeting the well-known port 22, so your logs get less cluttered and random guessing attempts drop. But it is security by obscurity, not real protection on its own: a port scanner such as nmap finds your port within seconds. Treat it as a nice complementary improvement on top of the real foundation: SSH keys, disabled password login, the firewall and Fail2ban.

Do I need all these layers for a small project? Yes, at least the basics. SSH keys, disabling root and password login, UFW and automatic updates are not "advanced hardening" but the minimum for any server on the internet, however small your project. Bots do not distinguish between big and small sites: they attack any exposed IP. You add the more advanced layers (2FA, AIDE) according to how sensitive your project is.

What is the difference between disabling root and deleting it? We disable root login over SSH (PermitRootLogin no); we do not delete the account. The root account stays in place and is essential for the system, but you no longer log in with it directly from the internet; instead, you log in as a regular user and elevate privileges with sudo. Deleting root itself is a bad idea that can break the system.

Is Fail2ban a replacement for SSH keys? No, they are two different, complementary layers. SSH keys prevent guessing in the first place (there is no password to guess). Fail2ban protects against flooding the server with connection attempts and also blocks attacks on other services. Real security combines the two as part of defense in depth, rather than one replacing the other.

Why should the database listen on localhost only? Because a web application on the same server reaches the database through 127.0.0.1 with no need to expose it to the internet. Leaving the database listening on 0.0.0.0 makes it a direct target for brute-force attacks and exploits from anywhere in the world. Listening locally eliminates this surface completely without affecting how your application works.

How often should I update the server? Security patches should be installed automatically every day through unattended-upgrades; this is not something to postpone. Major upgrades (OS releases, feature updates), on the other hand, should be applied manually each month or as needed, always after taking a backup and testing, so that a big update does not break your application unsupervised.

Can automatic updates break my site? The chance is small if you limit them to the security source (-security) only, as in the setup in this guide, because security patches are designed to be as backward compatible as possible. The risk comes from major feature upgrades, which is why we leave those to be applied manually. As a precaution, run backups daily so you can roll back if something unexpected happens.

What do I do if I discover my server really has been compromised? Disconnect it from the internet or stop the exposed services immediately, and do not trust the compromised server at all. The safest course is generally a clean rebuild: a new server, restoring data from a trusted backup made before the breach, changing every password and key, then applying this guide from scratch. Cleaning a compromised server "by hand" with complete confidence is almost impossible, because you do not know what the attacker planted.

Do I need a firewall if my provider has a cloud firewall? Yes, use both: this is defense in depth. The cloud firewall filters traffic before it reaches the server, and UFW filters at the level of the system itself as a second layer. If the cloud firewall is misconfigured or disabled, UFW is still your guard. Relying on a single layer goes against the whole principle of defense in depth.

Is two-factor authentication (2FA) for SSH necessary? It is not necessary in most cases if you use SSH keys with a strong passphrase, because the key alone is highly resistant to guessing. But it is valuable for highly sensitive servers or when several people access them, since it adds an independent factor (your phone), so possessing the key alone is not enough. Weigh the extra security against the setup complexity according to your server's sensitivity.

Is all this enough, or is there more hardening to do? This guide covers the strong core hardening that stops the overwhelming majority of automated attacks. For more sensitive environments, layers such as intrusion detection systems (IDS), network segmentation, auditd auditing, kernel hardening (sysctl) and isolated containers are added. But if you apply the checklist here in full, you are ahead of the vast majority of servers exposed on the internet.

Summary and final checklist

Hardening a VPS is not a task you do once and forget, but an ongoing practice of defense in depth: successive layers, each stopping whatever got past the one before. Start with the non-negotiable foundation (SSH keys, disabling root and password login, the UFW firewall and automatic updates), then add Fail2ban, attack surface reduction, monitoring and backups. And do not forget the golden rule at every sensitive step: a new session for testing before closing the old one, and knowing the way to your provider's console before you need it.

Review this checklist before you consider your server hardened:

✓ItemRequired state
☐A non-root user with sudo privilegesWorks and logs in successfully
☐SSH keysKey login works without a password
☐PermitRootLogin noEnabled and tested
☐PasswordAuthentication noEnabled and tested
☐AllowUsers setRestricts login to the allowed users
☐SSH port (optional)Opened in UFW before switching
☐UFW with a deny policy + SSH/80/443Enabled and status confirms it
☐Fail2ban on sshdRunning, with your IP in ignoreip
☐unattended-upgradesEnabled and tested with a dry run
☐Unnecessary services stoppedss -tulpn is clean
☐Databases on localhostNot listening on 0.0.0.0
☐Permissions on sensitive filesSet as in the table
☐Monitoring and logsReviewed regularly
☐Off-site backupsWorking, with restores tested

If you have completed every item on this checklist, you have built a hardened server that stands up to the vast majority of automated attacks and opportunistic attempts. Hardening is an ongoing journey, but this solid foundation is what separates an exposed server from a secure one.

Sources

Frequently asked questions

Does changing the SSH port really harden the server?

Changing the port greatly reduces the noise of automated scans targeting the well-known port 22, so your logs get less cluttered and random guessing attempts drop. But it is security by obscurity, not real protection on its own: a port scanner such as nmap finds your port within seconds. Treat it as a nice complementary improvement on top of the real foundation: SSH keys, disabled password login, the firewall and Fail2ban.

Do I need all these layers for a small project?

Yes, at least the basics. SSH keys, disabling root and password login, UFW and automatic updates are not "advanced hardening" but the minimum for any server on the internet, however small your project. Bots do not distinguish between big and small sites: they attack any exposed IP. You add the more advanced layers (2FA, AIDE) according to how sensitive your project is.

What is the difference between disabling root and deleting it?

We disable root login over SSH (PermitRootLogin no); we do not delete the account. The root account stays in place and is essential for the system, but you no longer log in with it directly from the internet; instead, you log in as a regular user and elevate privileges with sudo. Deleting root itself is a bad idea that can break the system.

Is Fail2ban a replacement for SSH keys?

No, they are two different, complementary layers. SSH keys prevent guessing in the first place (there is no password to guess). Fail2ban protects against flooding the server with connection attempts and also blocks attacks on other services. Real security combines the two as part of defense in depth, rather than one replacing the other.

Why should the database listen on localhost only?

Because a web application on the same server reaches the database through 127.0.0.1 with no need to expose it to the internet. Leaving the database listening on 0.0.0.0 makes it a direct target for brute-force attacks and exploits from anywhere in the world. Listening locally eliminates this surface completely without affecting how your application works.

How often should I update the server?

Security patches should be installed automatically every day through unattended-upgrades; this is not something to postpone. Major upgrades (OS releases, feature updates), on the other hand, should be applied manually each month or as needed, always after taking a backup and testing, so that a big update does not break your application unsupervised.

Can automatic updates break my site?

The chance is small if you limit them to the security source (-security) only, as in the setup in this guide, because security patches are designed to be as backward compatible as possible. The risk comes from major feature upgrades, which is why we leave those to be applied manually. As a precaution, run backups daily so you can roll back if something unexpected happens.

What do I do if I discover my server really has been compromised?

Disconnect it from the internet or stop the exposed services immediately, and do not trust the compromised server at all. The safest course is generally a clean rebuild: a new server, restoring data from a trusted backup made before the breach, changing every password and key, then applying this guide from scratch. Cleaning a compromised server "by hand" with complete confidence is almost impossible, because you do not know what the attacker planted.

Do I need a firewall if my provider has a cloud firewall?

Yes, use both: this is defense in depth. The cloud firewall filters traffic before it reaches the server, and UFW filters at the level of the system itself as a second layer. If the cloud firewall is misconfigured or disabled, UFW is still your guard. Relying on a single layer goes against the whole principle of defense in depth.

Is two-factor authentication (2FA) for SSH necessary?

It is not necessary in most cases if you use SSH keys with a strong passphrase, because the key alone is highly resistant to guessing. But it is valuable for highly sensitive servers or when several people access them, since it adds an independent factor (your phone), so possessing the key alone is not enough. Weigh the extra security against the setup complexity according to your server's sensitivity.

Is all this enough, or is there more hardening to do?

This guide covers the strong core hardening that stops the overwhelming majority of automated attacks. For more sensitive environments, layers such as intrusion detection systems (IDS), network segmentation, auditd auditing, kernel hardening (sysctl) and isolated containers are added. But if you apply the checklist here in full, you are ahead of the vast majority of servers exposed on the internet.