Your VPS is like a house, and the firewall is the front door. Without it, anyone can walk right in, searching for weaknesses. With a firewall in place, only trusted visitors can pass through, while everyone else stays out.
Your VPS needs the same protection. Without a strong firewall, you're leaving the door wide open for hackers, bots, and malicious traffic.
Cloudflare notes that in 2025, the number of DDoS attacks mitigated surged to 47.1 million, an average of 5,376 attacks every hour. They also highlight that 94% of all login attempts are now from bots, and approximately 30% of all HTTP traffic is bot-generated. A good firewall is the best way to block these ongoing threats.
In this guide, we’ll discuss everything you need to know to configure a VPS firewall, ensuring your server stays secure and performs well. Let’s get started!
What is VPS Hosting?
First of all, let's understand what VPS hosting is. VPS (Virtual Private Server) hosting splits a physical server into multiple virtual servers, offering dedicated resources like CPU, RAM, and storage. It provides more control and flexibility than shared hosting but is more affordable than dedicated servers. VPS hosting is ideal for businesses or developers needing more power, security, and customization. With root access, users can fully configure their server, making it suitable for high-traffic websites or complex applications requiring more control.
What is a VPS Firewall?
A VPS firewall is a security feature that controls the incoming and outgoing network traffic to a Virtual Private Server (VPS). Host-based firewalls operate at the operating system level, typically using rules defined through a command-line interface (CLI) with root access or via a server control panel, while cloud firewalls operate at the provider network perimeter.
The firewall acts as a barrier between your VPS and the internet, inspecting and filtering each network request before it reaches services like websites, databases, or SSH.
How it protects a VPS
A properly configured firewall is important for defending your VPS against various types of attacks, including:
Brute-force attacks: Attempts to gain unauthorized access by repeatedly trying different login credentials.
Port scanning: An attack method used to find open ports and services on the server to exploit.
DDoS attacks: Overloading server resources with excessive traffic to cause slowdowns or downtime.
Most VPS setups come with open ports by default, which can make the server vulnerable if not properly managed. That’s why setting up a structured firewall is essential from the start to control which ports are accessible and ensure only trusted traffic can reach the server.
Common Firewall Solutions for Linux VPS
Linux offers several firewall tools, each suited for different levels of expertise and use cases. Here's an overview of the most popular options:
Iptables
What it is: A powerful firewall utility that gives you full control over network traffic rules. It’s based on the Netfilter framework in the Linux kernel.
Best for: Experienced admins who need complete control over firewall configurations.
Pros: Highly flexible and customizable.
Cons: Requires manual configuration and can be complex for beginners.
Nftables
What it is: The modern replacement for iptables, designed for both IPv4 and IPv6. It's simpler to manage and often more efficient, especially for complex setups.
Best for: Newer systems or users looking for a more streamlined, performant solution.
Pros: Unified IPv4/IPv6 support, better performance.
Cons: May require some learning if coming from iptables.
UFW (Uncomplicated Firewall)
What it is: A simplified high-level frontend for managing Netfilter firewall rules (using the nftables backend by default on modern Ubuntu/Debian systems, and iptables on older releases). It’s the default for many Ubuntu-based systems.
Best for: Beginners or anyone who wants an easy way to set up basic firewall rules without much hassle.
Pros: Simple to use, ideal for small to medium setups.
Cons: Limited advanced features compared to iptables or nftables.
pfSense
What it is: A full firewall and routing platform, often installed as a virtual appliance. It offers a graphical interface for complete firewall and router management.
Best for: Users who want a comprehensive security solution with advanced features, ideal for network-level control.
Pros: Web-based interface, highly configurable.
Cons: Requires more resources and a complex setup.
Shorewall
What it is: A rule-based firewall system that uses configuration files to define the firewall setup. It’s built on Netfilter, like iptables and nftables.
Best for: Users who prefer structured, file-based configurations for complex environments.
Pros: Flexible, easier to scale for complex setups.
Cons: Requires understanding of the rule structure.
My Recommendation
For beginners or those using Ubuntu: Start with UFW. It's simple and works well for everyday use.
For more advanced setups: If you're comfortable with the command line and need more control, try Nftables. It’s the modern standard and works well for both IPv4 and IPv6.
For full network control: If you need a comprehensive firewall and router platform, pfSense offers a complete solution with a GUI.
Port Blacklisting vs Port Whitelisting
Controlling network ports is key to securing your VPS. By managing which ports are open, you can limit access to only the necessary services, reducing the risk of unauthorized access.
Here’s how Port Blacklisting and Port Whitelisting work:
Method | Description | Example | Benefit |
Port Blacklisting | Blocking specific, known vulnerable, or unused ports to reduce potential entry points for attackers. | Blocking unused ports like 23 (Telnet). | Reduces exposure to unnecessary services. |
Port Whitelisting | Allowing only specific trusted ports to be accessible, blocking all others by default. | Only allowing ports 22 (SSH), 80 (HTTP), and 443 (HTTPS). | Strictly controls access, limiting exposure to essential services. |
Step-by-Step Firewall Setup Guide
Before applying firewall rules, align your VPS firewall configuration with recognised security practices, including CIS Linux Benchmarks and NIST SP 800-41 Rev. 1. Use a single active Netfilter management framework, allow loopback (lo) traffic, and block spoofed loopback source addresses arriving through external interfaces. Also define stateful connection tracking and outbound traffic (egress) filtering policies. These baseline rules help control which connections your VPS accepts and which services can communicate externally.
Allow only required ports
Block unused services
Restrict unwanted IP access
Default deny rule for incoming traffic
Installation
Log in via SSH and update your system packages. Install your chosen firewall tool using the package manager:
For UFW (Ubuntu):
sudo apt update
sudo apt install ufw
For nftables:
sudo apt update
sudo apt install nftables
sudo systemctl enable --now nftables
Configuration
Set default policies to deny incoming traffic and allow outgoing connections. Permit established connections, loopback traffic, and only the required service ports.
Example for UFW:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
This blocks all other traffic except the specified ports.
Example for nftables:
First, create the configuration file:
sudo nano /etc/nftables.conf
Add the following rules:
#!/usr/sbin/nft -f
flush ruleset
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
iifname "lo" accept
iifname != "lo" ip saddr 127.0.0.0/8 drop
iifname != "lo" ip6 saddr ::1 drop
ct state established,related accept
ct state invalid drop
tcp dport { 22, 80, 443 } accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
Save the file and apply the rules:
sudo nft -f /etc/nftables.conf
sudo systemctl enable --now nftables
This configuration:
Drops incoming traffic by default.
Allows established and related connections.
Permits loopback traffic and blocks spoofed loopback addresses on external interfaces.
Opens TCP ports 22, 80, and 443.
Allows outgoing connections by default.
Important: Use only one active firewall management framework, such as UFW or native nftables. Avoid managing overlapping rules through UFW, nftables, and iptables simultaneously. If switching from UFW to native nftables, disable UFW first and ensure SSH access is permitted to avoid locking yourself out of the VPS.
Testing Rules
Keep your existing verification commands, but make sure readers run the command corresponding to their chosen firewall:
sudo ufw status verbose
sudo nft list ruleset
sudo iptables -L -v -n
Advanced Firewall Protection Techniques
Basic firewall rules control network access, but they do not cover every type of attack. Protecting an internet-facing VPS may also require host-level intrusion prevention, kernel TCP hardening, application-layer filtering, geographic traffic controls, and network-level access policies.
1. Fail2Ban for Blocking Repeated Login Attempts
Fail2Ban monitors server logs for repeated failed login attempts and temporarily blocks IP addresses that exceed the configured threshold.
Install Fail2Ban:
sudo apt update
sudo apt install fail2ban
Create a local configuration file:
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
Find the [sshd] section and configure:
[sshd]
enabled = true
port = ssh
bantime = 1h
findtime = 10m
maxretry = 5
Save the file and start the service:
sudo systemctl enable --now fail2ban
sudo systemctl restart fail2ban
Check the SSH protection status:
sudo fail2ban-client status sshd
Fail2Ban works alongside your host firewall by using its configured ban action. Make sure that action is compatible with your active firewall framework.
2. SYN Flood Protection and TCP Hardening
SYN cookies help protect the Linux TCP stack against SYN flood attacks by avoiding the allocation of connection state until the TCP handshake is completed.
Check the current setting:
sysctl net.ipv4.tcp_syncookies
Enable SYN cookies:
sudo nano /etc/sysctl.conf
Add:
net.ipv4.tcp_syncookies = 1
Apply the setting:
sudo sysctl -p
This is a kernel-level TCP protection setting, not a firewall rule. It helps handle SYN floods but does not replace upstream DDoS protection for high-volume attacks.
3. Web Application Firewall (WAF)
A Web Application Firewall inspects HTTP and HTTPS requests to identify malicious application-layer traffic, such as SQL injection and cross-site scripting attempts.
Unlike a traditional VPS firewall, which filters network connections and ports, a WAF examines web requests at Layer 7.
You can implement WAF protection through:
ModSecurity: An application-layer security module for supported web servers, including Apache and Nginx, commonly used with the OWASP Core Rule Set.
Cloudflare: An external proxy that filters web traffic before it reaches your VPS.
For Cloudflare, route your website through its proxy and configure available WAF rules in the Cloudflare dashboard. For a host-based setup, install ModSecurity and the OWASP Core Rule Set using instructions compatible with your web server and operating system.
4. GeoIP Filtering
GeoIP filtering controls access based on the geographic locations associated with source IP addresses. It can help restrict traffic from countries that have no legitimate reason to access specific services.
On Linux, host-level GeoIP filtering requires additional components, such as xt_geoip, or IP address sets managed through ipset or nftables.
With nftables, country IP ranges can be maintained in address sets and referenced in firewall rules to allow or drop traffic from selected regions.
Alternatively, you can apply geographic access restrictions through an external proxy such as Cloudflare.
Remember that GeoIP databases are not always accurate, and geographic filtering should not replace authentication or other access controls.
5. Network Access Control Lists (NACLs)
Network Access Control Lists are configured at the cloud provider or VPS network perimeter rather than inside the Linux operating system.
They control which traffic can enter or leave a network or subnet through provider-level rules.
Unlike stateful host firewalls such as UFW and nftables, NACLs are typically stateless. This means you must define both inbound and outbound rules, including the required ephemeral return ports for connections.
For example, a provider-level NACL may allow inbound traffic on ports 22, 80, and 443 while defining separate outbound rules for response traffic.
Check your hosting provider's network management console for NACL availability and configuration options. Not every VPS provider offers this feature.
Best Practices for Firewall Maintenance
Firewall setup is not a one-time task. Regular maintenance keeps systems stable and secure. Here are a few habits you can follow:
Switch to SSH keys and disable password login completely
Change the default SSH port to something less common.
Update your system and firewall software regularly.
Monitor logs with tools like fail2ban or simple log watchers.
Review your logs every few months for unusual activity
These steps go a long way toward a secure VPS firewall.
When to Choose Managed VPS
Setting up and maintaining a firewall takes time and knowledge. If you run a business site or several services, mistakes can cost downtime or data loss. Managed VPS hosting takes care of the firewall configuration, updates, monitoring, and advanced features like rate limiting or WAF for you.
Self-managed works fine if you enjoy learning the CLI and have time to handle security yourself. But when your project grows, or you want peace of mind, managed services let you focus on your work while experts keep everything locked down.
Conclusion
A properly configured VPS firewall forms the base of server protection. It filters traffic, reduces exposure, and controls how services are accessed. When combined with tools like Fail2Ban and WAF, it creates a layered defense approach suitable for modern hosting environments.
If you want help with setup or prefer not to manage firewall rules manually, a free consultation is available at Websouls. We also offer VPS hosting services with managed security, where firewall configuration and monitoring are handled as part of the system setup, helping keep everything stable and protected without extra effort.
FAQs on VPS Firewall Setup
What is a VPS firewall, and why do I need one?
A VPS firewall is a security tool that controls incoming and outgoing network traffic to your server. Without it, your VPS is exposed to potential threats like hackers, DDoS attacks, and automated bot traffic. It acts as a barrier between your server and the internet, only allowing trusted traffic through.
Which firewall tool should I use?
For beginners: UFW (Uncomplicated Firewall) is a simple tool, especially for Ubuntu users.
For advanced users: Iptables or nftables offer more granular control but require more expertise.
For complete protection, pfSense is a powerful firewall/router solution with a web interface, ideal for more complex setups.
Do I need to manually update firewall rules?
Yes, firewall rules should be reviewed periodically to make sure they reflect the current security needs of your VPS. However, tools like Fail2Ban can automate certain security tasks, such as blocking IPs after repeated failed login attempts.
What should I do if my VPS gets hacked?
If your VPS is compromised, take these steps:
Isolate the server: Block public traffic using provider-level firewall rules or disconnect its public network interface. Access it through your provider's out-of-band VNC/KVM console if available.
Preserve evidence: Take a disk snapshot for forensic investigation before making changes.
Review server logs: Check authentication logs (/var/log/auth.log), web server logs, system logs (journalctl), and firewall logs to investigate how the breach occurred.
Rebuild the VPS: Provision a fresh operating system image instead of relying on in-place repairs, as rootkits and backdoors may remain on a compromised system.
Restore clean backups: Patch the vulnerability that caused the breach and restore verified clean backups.
Rotate credentials: Change passwords, SSH keys, database credentials, API tokens, and TLS private keys from a clean environment.
Strengthen security: Configure Fail2Ban and strict firewall rules on the rebuilt server to help prevent future attacks.
How can I improve my firewall setup over time?
Regularly update your firewall software to stay protected from new threats. Implement advanced techniques like GeoIP Filtering or Fail2Ban to improve security. Monitor logs regularly to detect and block unusual behavior early. Consider integrating a Web Application Firewall (WAF) for additional protection from web-based attacks.







