How to Secure a VPS Server in 2026: 10 Essential Steps
To secure a VPS, update the operating system, create a separate administrator account, switch SSH to key-based authentication, restrict remote access, configure a firewall, protect login services, remove unused software, enable automatic security updates, deploy monitoring, and maintain tested off-server backups. These controls reduce common risks such as stolen passwords, exposed services, unpatched software, privilege abuse, malware, and unrecoverable data loss.
This guide uses Ubuntu 26.04 LTS commands for most examples. The same principles apply to Debian, AlmaLinux, Rocky Linux, and other server distributions, although package names, firewall tools, service names, and configuration paths may differ.
Important: Keep your current SSH session open while changing remote-access settings. Open a second session and confirm that it works before closing the first one. A firewall or SSH mistake can lock you out of the server.
VPS Security Checklist at a Glance
| Step | Security action | Main risk reduced |
|---|---|---|
| 1 | Update the operating system | Known software vulnerabilities |
| 2 | Create a non-root administrator | Direct privileged-account attacks |
| 3 | Use SSH keys | Password guessing and credential reuse |
| 4 | Harden SSH | Unnecessary remote-access exposure |
| 5 | Configure a firewall | Unwanted network access |
| 6 | Block repeated login attempts | Automated brute-force attacks |
| 7 | Remove unused services | Excess attack surface |
| 8 | Automate security updates | Delayed patching |
| 9 | Monitor logs and resources | Undetected incidents and failures |
| 10 | Back up and test recovery | Permanent data loss |
Before You Start: Record Your Recovery Options
Before applying security changes, confirm how you will recover if remote access stops working. Your VPS provider may offer a browser console, serial console, virtual KVM, rescue environment, recovery ISO, password reset, firewall panel, or snapshot feature.
Record the following information:
- The VPS public IP addresses.
- The provider account and recovery method.
- The current root or administrator access method.
- The server operating system and version.
- The SSH port.
- The provider console or rescue procedure.
- The current firewall rules.
- The location of backups and encryption keys.
Provider snapshots can be useful before major changes, but they should not be your only backup. A snapshot can share the same provider account, storage platform, and failure domain as the server.
Step 1: Update the Operating System
Security patches close known vulnerabilities in the kernel, system libraries, SSH server, web server, database, and installed applications. A newly deployed image may already be weeks or months behind the latest package state.
On Ubuntu or Debian, update the package index and install available upgrades:
sudo apt update
sudo apt upgrade -y
Check whether a reboot is required:
if [ -f /run/reboot-required ]; then
echo "Reboot required"
fi
If a reboot is needed, schedule it after confirming that critical services start automatically:
sudo reboot
After reconnecting, verify the system:
uname -r
systemctl --failed
Use a supported operating system
Security updates are available only while a release remains supported. Ubuntu 26.04 LTS was released in April 2026 and receives standard security maintenance through May 2031. Ubuntu 24.04 LTS also remains supported. Avoid starting a new production VPS on an end-of-life distribution.
Compare platform choices in Best Server OS in 2026. Users migrating away from CentOS can also review Best CentOS Replacements.
Review third-party repositories
Third-party repositories can create dependency conflicts, delay security patches, or install software outside the distribution’s support process. List configured APT sources:
grep -R --no-filename -h "^deb " /etc/apt/sources.list /etc/apt/sources.list.d/ 2>/dev/null
Keep only repositories that are required, trusted, documented, and actively maintained. Never copy installation commands from an unknown website directly into a root shell.
Step 2: Create a Separate Administrator Account
Direct root login gives an attacker a known username and complete privileges. Create a named user for normal administration and use sudo only when elevated access is required.
sudo adduser adminuser
sudo usermod -aG sudo adminuser
Replace adminuser with a unique account name. Confirm group membership:
id adminuser
Test the new account in a separate terminal:
ssh adminuser@SERVER_IP
sudo whoami
The final command should return root after successful authentication. Do not disable root access until this test succeeds.
Apply least privilege
Not every application user needs sudo access. Create separate service accounts for web applications, deployment tools, backups, databases, and automation. Limit each account to the files and commands it requires.
Review existing login-capable accounts:
awk -F: '$7 !~ /(nologin|false)$/ {print $1, $7}' /etc/passwd
Remove or lock accounts that are no longer needed, but first check scheduled tasks, file ownership, service units, and SSH keys associated with them.
Step 3: Configure SSH Key Authentication
SSH keys are stronger than reusable passwords when the private key is protected properly. Generate an Ed25519 key on your local computer:
ssh-keygen -t ed25519 -a 100
Use a strong passphrase. The private key remains on your computer; only the public key is copied to the server.
Copy the key with:
ssh-copy-id adminuser@SERVER_IP
If ssh-copy-id is unavailable, display the local public key:
cat ~/.ssh/id_ed25519.pub
Then add it to the server:
mkdir -p ~/.ssh
chmod 700 ~/.ssh
nano ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
Paste one complete public key per line. Test key authentication in a second terminal before changing password settings.
Protect the private key
- Use a passphrase.
- Do not email or upload the private key.
- Store a protected recovery copy.
- Use different keys for different administrators where practical.
- Remove keys immediately when access is no longer required.
- Review
authorized_keysfiles during access audits.
Step 4: Harden the SSH Server
OpenSSH settings are stored primarily in /etc/ssh/sshd_config and may also be provided through files in /etc/ssh/sshd_config.d/. A drop-in file can keep custom settings separate from the package-maintained configuration.
Create a hardening file:
sudo nano /etc/ssh/sshd_config.d/99-hardening.conf
A practical starting configuration is:
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
KbdInteractiveAuthentication no
MaxAuthTries 3
LoginGraceTime 30
AllowUsers adminuser
X11Forwarding no
Do not disable password authentication until key login has been tested successfully. If your environment uses SSH-based two-factor authentication, centralized authentication, automation accounts, or keyboard-interactive authentication, adapt the settings instead of copying them blindly.
Validate the configuration before reloading:
sudo sshd -t
If the command returns no output, reload SSH:
sudo systemctl reload ssh
Open a new terminal and confirm access. Keep the original session open until the new session works.
Should you change the SSH port?
Changing port 22 can reduce automated log noise, but it is not a replacement for keys, restricted access, patching, or a firewall. Attackers can scan other ports. When you change the port, update the provider firewall, host firewall, monitoring, documentation, and client configuration before reloading SSH.
Restrict SSH by source IP when possible
If administrators connect from fixed addresses or through a VPN, allow SSH only from those sources. This provides a much stronger reduction in exposure than changing the port.
Step 5: Configure a Firewall
A firewall should allow only services that the VPS intentionally provides. Ubuntu uses UFW as a convenient host-firewall interface.
Install UFW if required:
sudo apt install ufw -y
Set safe defaults:
sudo ufw default deny incoming
sudo ufw default allow outgoing
Allow SSH before enabling the firewall:
sudo ufw allow OpenSSH
If SSH uses a custom port, allow that port instead:
sudo ufw allow 2222/tcp
For a web server, allow HTTP and HTTPS:
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
Enable and inspect the firewall:
sudo ufw enable
sudo ufw status numbered
sudo ufw status verbose
Allow administration from one IP address
sudo ufw allow from 203.0.113.10 to any port 22 proto tcp
Replace the example address with your real administrative IP. Confirm that it is stable before removing broader access.
Do not expose databases unnecessarily
MySQL, MariaDB, PostgreSQL, Redis, and similar services should normally listen on localhost or a private network unless remote access is explicitly required. Public database ports attract automated attacks and can expose data when authentication is misconfigured.
Use Port Ping: How to Test a Specific Port to verify that required services are reachable and unwanted ports are closed.
Step 6: Block Repeated Login Attempts
SSH keys and firewall restrictions are the primary controls. A log-based banning tool can add protection by temporarily blocking addresses that generate repeated authentication failures.
Install Fail2ban:
sudo apt install fail2ban -y
Create a local SSH jail configuration:
sudo nano /etc/fail2ban/jail.d/sshd.local
Example:
[sshd]
enabled = true
backend = systemd
bantime = 1h
findtime = 10m
maxretry = 5
Restart and check the service:
sudo systemctl enable --now fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd
Do not set aggressive values without considering shared office networks, mobile connections, monitoring systems, or automation. Add trusted management addresses carefully to the ignore list only when necessary.
Provider firewall vs host firewall
A provider firewall can block traffic before it reaches the VPS, while UFW filters traffic on the server. Using both provides useful layers, but their rules must remain consistent. Document which layer allows each port.
Step 7: Remove Unused Software and Services
Every network service, package, user, and repository increases the system’s maintenance burden. Remove applications that are not required for the server’s purpose.
List listening services:
sudo ss -tulpn
List enabled services:
systemctl list-unit-files --type=service --state=enabled
List installed packages:
apt list --installed
Disable a service only after identifying its purpose:
sudo systemctl disable --now SERVICE_NAME
Remove an unnecessary package:
sudo apt purge PACKAGE_NAME
sudo apt autoremove --purge
Separate server roles
A public web server should not also become a general browsing computer, personal file store, test machine, and mail server. Combining unrelated roles increases exposure and makes recovery more difficult.
Use a suitable management interface when administering multiple services. Compare options in The Best Server Management Tool, Best Control Panel for Linux VPS, and Best Web Hosting Control Panel.
Step 8: Enable Automatic Security Updates
Ubuntu enables unattended security updates by default on many server images, but you should verify the configuration and monitoring. Install the package if needed:
sudo apt install unattended-upgrades -y
Check automatic update settings:
cat /etc/apt/apt.conf.d/20auto-upgrades
A common configuration contains:
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Unattended-Upgrade "1";
Test the configuration:
sudo unattended-upgrade --dry-run --debug
Review logs:
sudo less /var/log/unattended-upgrades/unattended-upgrades.log
Automatic updates still require operations planning
Security updates can restart services and occasionally require a reboot. Define maintenance windows, health checks, rollback procedures, and reboot monitoring. Critical production applications may require staged testing, but disabling security updates indefinitely creates a larger risk.
For kernel security fixes, Ubuntu Livepatch can apply many high and critical kernel updates without an immediate reboot. It does not remove the need for normal package updates or all future reboots.
Step 9: Monitor Logs, Resources, and File Changes
Security controls are incomplete without detection. Monitor the VPS for failed logins, new users, unexpected services, high CPU, low memory, disk pressure, certificate expiry, backup failures, and application errors.
Useful commands include:
systemctl --failed
journalctl -p warning --since today
sudo journalctl -u ssh --since today
last
lastb
df -h
free -h
uptime
sudo ss -tulpn
On Ubuntu, AppArmor provides mandatory access controls for supported applications and is installed and loaded by default. Check status:
sudo aa-status
Do not switch unfamiliar profiles directly into enforcement mode on a production server without testing. A restrictive profile can block legitimate application actions.
Build actionable alerts
Alert on conditions that need a response:
- Server unreachable.
- SSH service stopped.
- Disk above a defined threshold.
- High sustained CPU or load.
- Low available memory or active swapping.
- RAID or storage errors.
- Unexpected listening ports.
- Repeated authentication failures.
- Backup job failure.
- TLS certificate approaching expiry.
Compare tools in Best Linux System Monitor. Send alerts outside the VPS so they remain available when the server is offline.
Step 10: Create Tested Off-Server Backups
Backups protect against mistakes, malware, failed updates, application corruption, account compromise, and provider incidents. Store at least one recoverable copy outside the VPS and outside the production credentials where practical.
Back up:
- Application files.
- Databases.
- Web-server and service configuration.
- Firewall and SSH configuration.
- Certificates and renewal configuration.
- Scheduled tasks.
- Infrastructure documentation.
- Encryption keys through an appropriate secure process.
Define:
- Recovery point objective: how much recent data you can lose.
- Recovery time objective: how quickly the service must return.
- Backup schedule and retention.
- Encryption and access control.
- Restore-test schedule.
- Responsible person and escalation procedure.
Follow How to Back Up and Restore Data on a VPS for a detailed recovery workflow.
Additional VPS Security Controls
Use multi-factor authentication
Protect the hosting provider account, domain registrar, DNS provider, backup service, control panel, and monitoring account with multi-factor authentication. A secure VPS can still be deleted or reset through a compromised provider account.
Use a VPN or secure administration gateway
For sensitive environments, place SSH, RDP, database administration, and control panels behind a VPN or restricted management network. This reduces public exposure and centralizes administrative access.
Protect web applications separately
Server hardening does not fix vulnerable plugins, weak application passwords, insecure code, exposed admin panels, or outdated dependencies. Patch and test the application stack, use HTTPS, enforce secure cookies, limit upload execution, and monitor application logs.
Deploy endpoint protection where appropriate
Linux malware scanners and endpoint tools can detect selected threats, while Windows servers normally require more comprehensive endpoint protection. Review Best Antivirus Software for Servers. Exclusions should be narrow and justified; broad exclusions can hide attacks.
Document every security change
Record why a port is open, who owns each account, where keys are stored, how backups are restored, and how the server is rebuilt. Documentation reduces recovery time and prevents a future administrator from weakening controls simply to make a service work.
Security Verification Commands
| Check | Command |
|---|---|
| Operating-system version | cat /etc/os-release |
| Available updates | apt list --upgradable |
| Failed services | systemctl --failed |
| Listening ports | sudo ss -tulpn |
| Firewall status | sudo ufw status verbose |
| SSH effective settings | sudo sshd -T |
| Fail2ban status | sudo fail2ban-client status |
| AppArmor status | sudo aa-status |
| Recent login history | last |
| Disk usage | df -h |
Common VPS Security Mistakes
- Disabling passwords before testing SSH keys: this can lock you out.
- Enabling UFW before allowing SSH: the active session may survive while new connections fail.
- Opening every port temporarily and forgetting: temporary rules often become permanent exposure.
- Using one root password across servers: one credential leak compromises the fleet.
- Ignoring renewal and support dates: end-of-life systems stop receiving normal security fixes.
- Treating Fail2ban as primary protection: keys, firewall restrictions, and patching are more important.
- Keeping unnecessary control panels and services: every application requires updates and monitoring.
- Storing backups on the same VPS: one incident can remove both production and recovery copies.
- Relying on a provider snapshot alone: snapshots do not replace independent backups and restore tests.
- Installing random scripts as root: inspect scripts and use trusted package sources.
- Ignoring provider-account security: an attacker may reset, copy, or delete the server through the dashboard.
- Never reviewing logs: security events can continue unnoticed for months.
Monthly VPS Security Maintenance Checklist
- Review failed login attempts and privileged actions.
- Confirm all security updates are installed.
- Check whether a reboot is required.
- Review users, sudo access, and authorized SSH keys.
- Inspect listening ports and firewall rules.
- Verify monitoring and alert delivery.
- Check backup completion and perform a sample restore.
- Review disk, memory, and CPU trends.
- Remove unused packages and repositories.
- Confirm certificates are renewing.
- Review provider-account access and multi-factor authentication.
- Update recovery documentation.
Secure Secrets, API Keys, and Application Credentials
VPS security also depends on how applications store passwords, database credentials, API tokens, private keys, and encryption secrets. A firewall cannot protect a secret that is committed to a public repository, printed in a log, or stored in a world-readable configuration file.
Use these practices:
- Keep secrets outside public source-code repositories.
- Restrict configuration-file permissions to the service account that needs them.
- Use separate credentials for development, staging, and production.
- Rotate credentials after staff changes, suspected exposure, and major incidents.
- Avoid passing secrets directly on a command line when they can appear in process listings or shell history.
- Use a password manager or secrets-management system for administrative credentials.
- Give database users only the permissions required by the application.
- Do not reuse provider, root, database, application, and backup passwords.
Check sensitive file permissions:
find /etc -xdev -type f -perm /o+r 2>/dev/null | less
find /home -xdev -type f -name "authorized_keys" -ls
These commands produce review lists rather than automatic proof of a problem. Many files in /etc are intentionally readable. Investigate before changing permissions because an incorrect restriction can prevent services from starting.
Create a VPS Incident Response Plan
A security plan should define what happens after suspicious activity is detected. Improvised responses can destroy evidence, spread the incident, or make recovery slower.
Prepare a written process that covers:
- Detection: identify the alert, affected service, time range, and evidence source.
- Containment: restrict network access, disable compromised accounts, or isolate the VPS through the provider firewall.
- Preservation: save relevant logs, process lists, connection data, and configuration before rebuilding.
- Credential rotation: change provider, SSH, database, application, API, DNS, and backup credentials that may be exposed.
- Eradication: remove the cause or rebuild from a trusted image rather than assuming every malicious change was found.
- Recovery: restore verified data, patch the vulnerability, test the service, and monitor closely.
- Review: document the root cause and update controls, alerts, and procedures.
When the integrity of a root-accessible server is uncertain, rebuilding from a clean supported image is often safer than attempting to clean the existing installation. Restore only verified application data and configuration.
VPS Security by Workload
| Workload | Extra controls to prioritize |
|---|---|
| WordPress or CMS | Plugin and theme updates, limited file permissions, web application firewall, protected admin login |
| E-commerce | Payment-scope review, strict admin access, file-integrity monitoring, rapid restore capability |
| Database server | Private listening address, encrypted connections, least-privilege database users, point-in-time recovery |
| Mail server | Anti-abuse monitoring, correct DNS, relay restrictions, account protection, reputation alerts |
| Game server | DDoS protection, plugin and mod review, separate service user, resource limits |
| Developer server | Repository access control, secret scanning, isolated build users, restricted deployment keys |
| Forex VPS | Restricted RDP or SSH, protected trading credentials, application monitoring, tested standby plan |
The base ten-step process applies to every VPS, but application-specific threats require additional controls. Review the application vendor’s security guidance and remove default accounts, sample applications, and unused administrative interfaces before launch.
Test Security Without Breaking Production
Security verification should be controlled and authorized. Begin with configuration and exposure checks rather than aggressive scanning.
- Test SSH from an approved external network.
- Confirm root and password authentication behave as intended.
- Verify only documented ports are reachable.
- Trigger a test monitoring alert.
- Confirm a blocked address can be safely unblocked through the provider console.
- Restore a sample file and a test database.
- Confirm a new administrator can follow the recovery documentation.
- Review the server after updates and application deployments.
Run major firewall, SSH, and authentication changes during a maintenance period. Preserve one working session and provider-console access until the change is fully verified.
Final VPS Security Checklist
- The operating system is supported and fully patched.
- A named administrator account works with sudo.
- SSH key access has been tested.
- Direct root login is disabled.
- Password login is disabled when compatible with the environment.
- Only required ports are open.
- Repeated login failures are monitored or blocked.
- Unused services and packages are removed.
- Automatic security updates are configured and reviewed.
- Logs, resources, and service health are monitored.
- Provider accounts use multi-factor authentication.
- Backups are stored off-server and have been restored successfully.
- Recovery-console access is documented.
- Security responsibilities are assigned to a person or team.
Final Verdict
A secure VPS is not created by one command or one security tool. It is built from layers: supported software, limited privileges, protected remote access, a default-deny firewall, reduced attack surface, timely patching, monitoring, and recoverable backups.
Start with SSH access and firewall safety, then remove unnecessary services and automate routine maintenance. Verify every change from a second session, keep recovery-console access available, and test backups before the server becomes critical. Security is an ongoing operating process rather than a one-time installation task.
Frequently Asked Questions
What is the first thing I should do to secure a VPS?
Update the operating system, confirm recovery-console access, and create a separate administrator account before changing SSH or firewall settings.
Should I disable root login on a VPS?
Yes, after a tested sudo-enabled administrator account is available. Disabling direct root login reduces exposure of a known privileged username.
Should I disable SSH password authentication?
Yes when every required user has tested key-based access and a recovery method exists. Environments using specialized authentication may require different settings.
Does changing the SSH port secure a VPS?
It reduces automated log noise but does not replace SSH keys, firewall restrictions, updates, and monitoring.
Is UFW enough to protect a VPS?
UFW is an important network control, but security also requires patching, strong authentication, least privilege, application security, monitoring, and backups.
Do I need Fail2ban if I use SSH keys?
It is optional. SSH keys and source-IP restrictions provide stronger protection, while Fail2ban can reduce repeated automated attempts and log noise.
Are automatic updates safe on a production VPS?
Automatic security updates reduce patch delay, but production systems should also have monitoring, maintenance planning, health checks, and recovery procedures.
Does a VPS need antivirus?
It depends on the operating system and workload. Antivirus or endpoint protection can add value, but it does not replace patching, access control, firewalls, and backups.
Are provider snapshots enough for backup?
No. Maintain an independent off-server backup with retention and tested restoration.
How often should I audit VPS security?
Monitor continuously, review critical alerts daily, apply updates regularly, and perform a structured access, firewall, backup, and configuration review at least monthly.