Skip to content

The Complete Beginner’s Guide to Securing a Linux VPS

The Complete Beginner’s Guide to Securing a Linux VPS (Step-by-Step)

The moment your Virtual Private Server (VPS) finishes booting and is assigned a public IPv4 address, it becomes a target. Within minutes, automated bots and malicious scanners sweep the entire IPv4 space, probing for open ports, unpatched software, and weak default credentials. Leaving a freshly deployed cloud server unhardened is an open invitation to cryptominers, ransomware, and botnet hijacking.

Fortunately, securing a Linux VPS does not require an advanced cybersecurity degree. By establishing a layered defense-in-depth posture during your initial server setup, you can neutralize more than 99% of automated brute-force attacks and vulnerability scans. Effective server hardening is not a single command; it is a systematic process of shrinking your attack surface, locking down remote access, hardening kernel network parameters, and enabling continuous intrusion prevention.

In this beginner-friendly handbook, we walk through the exact, battle-tested pipeline for securing a Linux VPS—applicable to Ubuntu, Debian, AlmaLinux, and Rocky Linux—so your production server remains protected without slowing down your daily administration workflow.

Step-by-step diagram of securing a Linux VPS using SSH keys, UFW firewall, and Fail2ban
Securing a Linux VPS relies on layered defense: combining SSH key authentication, host firewalls, least-privilege sudo users, and automated intrusion prevention.

The 15-Minute Checklist for Securing a Linux VPS

If you have just launched a brand-new server, run through this priority matrix immediately. Completing these nine foundational tasks forms the core baseline for securing a Linux VPS against automated internet threats:

Security Step Vulnerability Addressed Admin Command / Configuration Priority
1. Update All Packages Unpatched exploits and known CVEs apt update && apt upgrade or dnf update Critical (Immediate)
2. Add Sudo User Running routine admin tasks as root adduser username && usermod -aG sudo username Critical (Immediate)
3. Configure SSH Keys Password guessing and brute-force bots ssh-keygen & ssh-copy-id -i ~/.ssh/id_ed25519.pub user@ip Critical (Immediate)
4. Harden SSH Daemon Direct root login & password attacks PermitRootLogin no & PasswordAuthentication no Critical (Immediate)
5. Enable Host Firewall Exposure of internal background ports ufw default deny incoming or firewall-cmd Critical (Immediate)
6. Install Fail2ban Resource exhaustion from repeated scans Install and configure fail2ban for SSH jails Important (Day 1)
7. Automate Security Patches Manual update delays over time unattended-upgrades or dnf-automatic Important (Day 1)
8. Harden Kernel Network IP spoofing, SYN floods, and MITM redirects Configure /etc/sysctl.d/99-security.conf Recommended
9. Run Security Audit Hidden misconfigurations and weak permissions Run sudo lynis audit system Recommended

Step 1: Update and Patch System Packages Immediately

The easiest way for an attacker to breach a server is through unpatched software. Operating system vendors constantly publish security advisories for vulnerabilities discovered in OpenSSL, the Linux kernel, systemd, and core network utilities. Because cloud provider OS templates are often built weeks or months prior to deployment, updating packages is the mandatory first action when securing a Linux VPS.

Before installing applications or modifying firewall rules, connect to your VPS via SSH and bring every installed package up to date:

For Ubuntu and Debian:

# Refresh the local package index
sudo apt update

# Install all available security and software upgrades
sudo apt upgrade -y

# Remove obsolete dependencies and cached package archives
sudo apt autoremove -y && sudo apt autoclean

For AlmaLinux and Rocky Linux:

# Update all installed packages to their latest stable releases
sudo dnf update -y

# Clean up unused dependencies
sudo dnf autoremove -y

If a kernel update was installed during this step, reboot your server (sudo reboot) so the patched kernel loads into memory before you proceed. If you are still deciding which operating system offers the longest patch lifecycle and cleanest security defaults for your workload, read our guide on choosing the best Linux distro for VPS hosting.

Step 2: Create a Dedicated Administrative (Sudo) User

Most VPS providers provision your instance with a default root account. Because root has unrestricted authority to modify kernel parameters, delete system files, and read every directory on the machine, automated attackers target the root username relentlessly.

A core principle of securing a Linux VPS is enforcing the Principle of Least Privilege: never log in directly as root for routine administration. Instead, create a dedicated non-root user account and grant it elevated sudo privileges only when executing administrative commands. This creates an audit trail in system logs and prevents accidental destructive commands from wiping critical system directories.

1. Create a new user account:

# Replace 'sysadmin' with your preferred administrative username
sudo adduser sysadmin

Set a strong, unique password when prompted (you will need this password when running sudo commands), and press Enter through the optional full name and room number fields.

2. Grant elevated sudo privileges:

Depending on your Linux distribution family, add your new user to either the sudo group or the wheel group:

# For Ubuntu & Debian:
sudo usermod -aG sudo sysadmin

# For AlmaLinux & Rocky Linux:
sudo usermod -aG wheel sysadmin

3. Verify sudo permissions before proceeding:

# Switch into the new user account
su - sysadmin

# Test sudo privilege elevation
sudo whoami

If the terminal prints root after you enter your user password, your new administrative account is properly configured.

Step 3: Switch to Cryptographic SSH Key Authentication

Passwords—even complex 16-character strings—are susceptible to credential stuffing, keyloggers, and relentless brute-force bots. When securing a Linux VPS, replacing password logins with OpenSSH cryptographic key pairs eliminates password-guessing attacks completely.

An SSH key pair consists of two mathematically linked files: a public key placed on your VPS inside ~/.ssh/authorized_keys and a private key kept strictly on your local workstation. Without your physical private key file, an attacker cannot authenticate—even if they know your username and password.

Diagram showing SSH public and private key authentication when securing a Linux VPS
Cryptographic Ed25519 SSH keys replace vulnerable passwords and stop automated brute-force login bots.

1. Generate an Ed25519 key pair on your local machine:

Open a terminal on your local computer (Linux, macOS, or Windows PowerShell) and generate a modern Ed25519 SSH key pair, which offers superior cryptographic strength and faster verification than legacy RSA keys:

# Generate a fast, modern Ed25519 SSH key pair
ssh-keygen -t ed25519 -C "vps-admin-key"

Accept the default file path (~/.ssh/id_ed25519) and enter a strong passphrase to encrypt your private key on disk. Adding a passphrase ensures that even if someone gains access to your laptop, they still cannot use your SSH key without unlocking it.

2. Copy your public key to the VPS:

# Upload your public key to your new non-root user
ssh-copy-id -i ~/.ssh/id_ed25519.pub sysadmin@your_vps_ip

If you are working from a Windows terminal that lacks ssh-copy-id, you can copy the contents of your local id_ed25519.pub file and append it manually on the server using strict file permissions:

# Manual alternative on the VPS if ssh-copy-id is unavailable
mkdir -p ~/.ssh
chmod 700 ~/.ssh
echo "paste_your_public_key_string_here" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys

3. Verify key-based SSH login:

Open a separate terminal window on your local machine and test connecting to your server:

# Log in using your SSH key
ssh sysadmin@your_vps_ip

If you are prompted for your SSH key passphrase (rather than the remote user’s Linux password), key authentication is working properly.

Step 4: Harden the SSH Daemon (sshd_config)

Once your non-root user can log in reliably using an SSH key, it is time to lock down the SSH daemon itself. Disabling direct root login, turning off password authentication, and tightening idle session timeouts are among the highest-impact steps in securing a Linux VPS.

Open the SSH daemon configuration file on your VPS:

sudo nano /etc/ssh/sshd_config

Locate and update the following directives (uncommenting them by removing any leading # symbol):

# Block direct root logins over SSH
PermitRootLogin no

# Disable password-based SSH authentication completely
PasswordAuthentication no

# Disable interactive challenge-response passwords and empty passwords
ChallengeResponseAuthentication no
PermitEmptyPasswords no

# Restrict SSH access exclusively to your administrative user
AllowUsers sysadmin

# Disconnect idle SSH sessions after 10 minutes (300s x 2)
ClientAliveInterval 300
ClientAliveCountMax 2

# Limit maximum authentication attempts per connection
MaxAuthTries 3

Save and close the editor (Ctrl+O, Enter, then Ctrl+X in Nano).

CRITICAL SAFETY CHECK: Always test your SSH configuration syntax before restarting the daemon so a typo never locks you out of your server:

# Validate sshd_config syntax (returns nothing if valid)
sudo sshd -t

# Restart the SSH service to apply your hardened policy
sudo systemctl restart sshd

Keep your current terminal session open while testing a fresh SSH connection in a second window to confirm everything works as expected.

Step 5: Configure and Enable a Host-Based Firewall

Even on a minimal server, internal services like databases, Redis caches, or Docker containers can accidentally bind to public network interfaces. Configuring a host-level firewall is essential when securing a Linux VPS because it drops all unsolicited inbound traffic by default while permitting only explicitly approved ports.

For Ubuntu and Debian (UFW Firewall):

# Deny all incoming connections by default
sudo ufw default deny incoming

# Allow all outbound connections
sudo ufw default allow outgoing

# Allow SSH, HTTP, and HTTPS traffic
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# Enable UFW and verify active rules
sudo ufw enable
sudo ufw status verbose

For AlmaLinux and Rocky Linux (firewalld):

# Permit SSH, HTTP, and HTTPS permanently
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https

# Reload firewalld and inspect active rules
sudo firewall-cmd --reload
sudo firewall-cmd --list-all

Docker Warning: If you run Docker containers on your VPS, remember that Docker manipulates iptables directly and can bypass UFW rules if you publish ports using -p 8080:80. Always bind internal container ports to localhost (-p 127.0.0.1:8080:80) behind a reverse proxy. To audit which ports are listening on your public IP address, use the ss -tulpn command covered in our essential Linux commands for VPS owners handbook.

Terminal output showing UFW firewall rules configured while securing a Linux VPS
A properly configured UFW firewall blocks all unsolicited inbound connections while allowing only SSH, HTTP, and HTTPS.

Step 6: Block Brute-Force Bots with Fail2ban

Even after disabling password logins, automated scanners will continue hammering your SSH port, filling up /var/log/auth.log and wasting CPU cycles on cryptographic handshakes. Installing Fail2ban adds automated intrusion prevention to your strategy for securing a Linux VPS by monitoring authentication logs and dynamically banning offending IP addresses at the firewall level.

1. Install Fail2ban:

# Ubuntu & Debian:
sudo apt install fail2ban -y

# AlmaLinux & Rocky Linux:
sudo dnf install epel-release -y
sudo dnf install fail2ban -y

2. Create a local jail.local configuration file:

Never edit jail.conf directly, as package updates can overwrite it. Copy it to jail.local instead:

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

Configure the [DEFAULT] and [sshd] jail blocks so repeated failed attempts trigger an automatic 1-hour ban, and add your static home or office IP to ignoreip so you never lock yourself out:

[DEFAULT]
ignoreip = 127.0.0.1/8 ::1 your_static_home_ip

[sshd]
enabled  = true
port     = ssh
logpath  = %(sshd_log)s
backend  = %(sshd_backend)s
maxretry = 5
findtime = 10m
bantime  = 1h

3. Enable and verify Fail2ban:

sudo systemctl enable --now fail2ban
sudo fail2ban-client status sshd

Within minutes of enabling Fail2ban on a public VPS, you will typically see the Currently banned counter climb as automated scanners get blocked automatically.

Step 7: Enable Automatic Security Updates

Long-term success in securing a Linux VPS depends on consistent patching. Zero-day vulnerabilities in web servers, OpenSSL, or network libraries are weaponized within hours of disclosure. Enabling automatic security updates ensures critical vulnerability fixes are applied promptly even when you are away from your terminal.

For Ubuntu and Debian:

# Install unattended-upgrades
sudo apt install unattended-upgrades -y

# Enable automatic security updates interactively
sudo dpkg-reconfigure --priority=low unattended-upgrades

For AlmaLinux and Rocky Linux:

# Install dnf-automatic
sudo dnf install dnf-automatic -y
sudo nano /etc/dnf/automatic.conf

Inside automatic.conf, set upgrade_type = security and apply_updates = yes, then enable the systemd timer:

sudo systemctl enable --now dnf-automatic.timer

Step 8: Harden Kernel Network Parameters (sysctl)

Beyond application-level firewalls, the Linux kernel itself includes built-in TCP/IP stack protections against SYN flood attacks, IP address spoofing, and ICMP redirect man-in-the-middle attacks. Tuning kernel parameters via sysctl is a lightweight, zero-overhead addition when securing a Linux VPS.

Create a dedicated hardening file inside /etc/sysctl.d/:

sudo nano /etc/sysctl.d/99-vps-hardening.conf

Add the following production-safe network security directives:

# Protect against TCP SYN flood attacks
net.ipv4.tcp_syncookies = 1

# Enable reverse path filtering to block IP spoofing
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1

# Ignore ICMP broadcast requests (prevents Smurf DDoS amplification)
net.ipv4.icmp_echo_ignore_broadcasts = 1

# Disable ICMP redirects to prevent routing table manipulation
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0

# Disable source-routed packets
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0

Save the file and reload your kernel settings immediately:

sudo sysctl --system

Step 9: Audit Your Server with Lynis & Private VPN Access

Once your core defenses are active, you can validate your hardening progress and take your security posture to an enterprise level using two final practices:

  • Run a Lynis Security Audit: Install the open-source Lynis security auditing tool (sudo apt install lynis -y or sudo dnf install lynis -y) and run sudo lynis audit system. Lynis scans hundreds of Linux kernel parameters, file permissions, SSH configurations, and installed packages, producing a numerical Hardening Index along with specific actionable warnings.
  • Hide SSH Behind a Private VPN: For maximum protection when securing a Linux VPS, deploy WireGuard or Tailscale and restrict SSH access exclusively to your private VPN interface (for example, sudo ufw allow in on wg0 to any port 22), then remove the public SSH rule. Your SSH port becomes completely invisible to public internet scanners. Check our guide on the best self hosted apps for VPS deployments for a quick WireGuard setup.
  • Bind Internal Services to Localhost: Verify that databases (MySQL, PostgreSQL, Redis) and internal application backends bind strictly to 127.0.0.1 rather than 0.0.0.0, preventing external exposure even if firewall rules are temporarily flushed.

Frequently Asked Questions (FAQ)

How long does securing a Linux VPS take for a beginner?

Completing all nine essential steps—updating packages, creating a sudo user, setting up SSH keys, hardening sshd_config, enabling UFW/firewalld, configuring Fail2ban, turning on automatic security updates, tuning sysctl, and running an audit—takes roughly 20 to 25 minutes on a fresh server.

Should I change the default SSH port (22) when securing a Linux VPS?

Moving SSH to a non-standard high port (such as 2222 or 49152) is a helpful secondary measure that dramatically reduces automated bot noise in your logs. However, it is “security through obscurity” and should always be paired with SSH key authentication and a firewall rather than treated as a standalone security fix.

What should I do if I lock myself out of my VPS while configuring SSH or UFW?

Every major VPS provider includes a web-based VNC or Emergency Serial Console inside your hosting control panel. Because this console attaches directly to the virtual machine’s virtual display rather than over SSH, you can log in locally with your sudo user’s password and fix any typo in /etc/ssh/sshd_config or reset UFW rules.

Do I still need Fail2ban if I disabled SSH password authentication?

Yes. Even though bots cannot guess an Ed25519 SSH key, unblocked scanners will repeatedly initiate SSH handshakes, consuming CPU, memory, and disk space in auth.log. Fail2ban drops repeat offenders at the firewall layer so your server resources stay dedicated to your live applications.

Final Summary Checklist for Securing a Linux VPS

Following a structured workflow for securing a Linux VPS protects your websites, databases, and user data from automated attacks from day one. Before deploying live applications onto your server, verify that every item on this final baseline is active:

  1. System Packages: All OS packages and libraries are fully updated and automatic security patching is active.
  2. Access Control: Routine tasks run under a non-root sudo user, while direct root SSH login and password authentication are disabled.
  3. Network Perimeter: Your host firewall (UFW or firewalld) drops all unsolicited inbound traffic except required service ports, backed by hardened sysctl kernel rules.
  4. Active Intrusion Prevention: Fail2ban is actively monitoring SSH logs and banning brute-force IPs automatically.

With these core defenses locked in place and paired with automated off-site backups, your Linux VPS is ready for reliable, production-grade hosting.