Firewall Configuration Guide For Linux VPS (Step-by-Step)

Firewall Configuration Guide For Linux VPS (Step-by-Step)

Firewall Configuration Guide For Linux VPS (Step-by-Step) blog

A firewall configuration guide for Linux VPS becomes essential the moment your server touches the internet, which, honestly, is almost immediately. Even small personal projects attract scans and random traffic.

In this guide, we’ll break things down simply. We’ll explain why specific ports exist, and show how to secure your VPS without overcomplicating it.

Configuring a firewall is a key step in securing any Linux VPS environment. The comparison table below highlights VPS hosting providers that support flexible firewall setups and reliable network performance. These providers help ensure your server remains protected without limiting connectivity. Explore our recommended VPS hosting options.

Linux VPS Hosting Providers With Strong Network Security Capabilities

ProviderUser RatingRecommended For 
Kamatera Logo4.8ScalabilityVisit Kamatera
4.6AffordabilityVisit Hostinger
4.7DevelopersVisit IONOS

Takeaways
  • A firewall is not optional on a Linux VPS—it’s essential.
  • Understanding port numbers prevents accidental exposure.
  • UFW, Firewalld, Iptables, and Nftables serve different needs.
  • Persistent rules save you from surprises after a reboot.
  • Testing and monitoring are just as crucial as setup.

Understanding the Role of a Network Security System on Linux.

A firewall is like a doorman for your Linux VPS. It is the first point of contact for anyone who wants to enter the system.

It is always on the lookout to ensure that only authorized personnel gain access to the system. It does this for both outgoing and incoming traffic. That is done through a set of rules that distinguish between authorized and unauthorized access.

When the firewall is configured correctly, it prevents unauthorized access to specific ports. That includes the SSH (port 22) or MySQL (port 3306). It also ensures brute-force attacks do not compromise the system.

The filters are what ensure the integrity of the data on the Virtual Private Server (VPS). They are the tools that the operating system uses to distinguish between authorized and unauthorized access.

Classification of Linux Ports: From Well-Known to Ephemeral

To configure your firewall intelligently, it is vital to understand the different classifications of port numbers.

  • Well-Known Ports (0-1023): These are the reserved ports typically used for services such as HTTP (port 80), HTTPS (port 443), and SSH (port 22). These are the standard ports for all Linux platforms. Root access is needed to bind any process to these ports.
  • Registered/User Ports (1024-49151): These are the ports used to provide services to specific applications. Your custom applications will be using these ports to listen for incoming requests.
  • Dynamic/Private Ports (49152-65535): These are the ports typically used for ephemeral communication. These are typically assigned when you are sending a request.

It is vital to understand the different port classifications to develop a precise guide for configuring the firewall on the Linux VPS. The Internet Assigned Numbers Authority is the hub for all configuration data.

IANA website showing port numbers.

Essential Prerequisites for Managing Firewall Rules

Before you modify anything, a few essentials must be in place.

  • Terminal Access: Knowing your way around the terminal matters, especially when using SSH. Instead of clicking buttons, tasks on the firewall often need to be handled from the command prompt, not the visual screen. 
  • Sudo Privileges: To modify firewall rules, admin access matters most. Without it, running setup commands becomes impossible due to access restrictions. Special permission controls what changes take effect here.
  • Console Access: Here’s something worth remembering. You can lock yourself out if you lose access. So keep a way in, like the web console your Linux VPS service offers.
  • Service Audit: The service audit shows that ports must be accessible for active services. When ports stay closed, risks drop. Every active port becomes one door hackers might try.

3 Benefits of a Robust Firewall Configuration Guide for Linux VPS

Every day, bot programs search for weaknesses in server setups. A firewall blocks such attempts before they go further.

1. Preventing Unauthorized Intrusion

It blocks harmful scans along with repeated login attempts on key ports. Scanning tools run nonstop like rogue bots searching for weaknesses. Thereafter, a firewall steps in, halting any malicious advance right there.

It keeps the management door locked to just approved IP addresses. That adds another layer of protection beyond simple password logins.

2. Enhancing Server Performance

Reduces CPU usage by rejecting suspicious traffic before it reaches the application layer. Your server will not have to waste resources on users identified as malicious actors.

Protecting against DDoS attacks and botnet traffic stops network strain. Resources stay free for real users accessing your server.

3. Meeting Compliance Standards

GDPR homepage.

Protecting data follows rules like PCI-DSS and GDPR. Firewalls help meet those needs. Most data protection regulations explicitly require the implementation of firewalls as a minimum security requirement.

What stands out is how it shows you take user safety seriously. Security layers stack up when trust builds slowly through absolute protection. Knowing that data is being safeguarded leads people to lean toward a service without hesitation.

Step 1: Auditing Your Current Port Status

Before you begin modifying the firewall rules, check which ports are currently open for listening. That way, you won’t accidentally cut off an essential service. To see every open listening port, run ‘netstat -lntu’. The ports are displayed numerically.

Another option is to run ‘ss -lntu’, which displays socket stats in a clear format. This tool has been tuned to work well on today’s Linux distros without slowing things down.

To see if something is open on a specific port, try running ‘netstat -lntu | grep 443’. The command looks for activity on port 443.

Step 2: Implementing the Uncomplicated Firewall (UFW) on Ubuntu

A transparent firewall stands behind UFW’s design. Built into Debian platforms by standard practice. It’s a framework that simplifies complex firewall rules into readable commands. It’s ideal for Ubuntu-based Linux systems.

Basic Command: To get started, you install UFW and activate it:

  • Install UFW
  • sudo ufw enable

That single command—sudo ufw enable—turns on protection immediately.

Port Ranges: UFW allows ranges, which is helpful if your application uses multiple ports. That keeps rule sets concise and easier to manage.

Ultahost

Launch, Scale, and Manage your website with high-performance Web Hosting and VPS.
Visit Site Coupons6

Step 3: How to Check sudo ufw status

You can use the command “sudo ufw status” to get a comprehensive list of the active rules with their corresponding action. Whether it is “Allow” or “Deny.”

To see the index number for each rule, use “sudo ufw status numbered.” That’ll help spot the exact rule you’re adjusting right away.

Look at the firewall status. Is it turned on or off? When set to off, all protections are disabled, allowing attackers to target your server easily.

Step 4: Allowing and Denying traffic via sudo ufw

Firewall setup with sudo ufw.

Do you want to block a specific IP address, such as 192.168.1.1? Try “sudo ufw deny from 192.168.1.1.” That stops all traffic, regardless of port or protocol. Rules apply just to that address.

To allow SSH, type “sudo ufw allow 22/tcp” into your terminal. Make sure the connection stays protected for security reasons. Security comes first here. That’s because it’ll be your primary way to manage the server.

The following command that you will use is: “sudo ufw enable”. That’ll activate your configuration immediately.

After shutting down, the changes made with sudo ufw get stored without extra steps. These settings remain even if the machine reboots.

Step 5: Managing Firewalld for CentOS, RHEL, and AlmaLinux

Firewalld is a dynamic daemon that uses “zones” to manage traffic levels. A zone refers to different levels of trust for network interfaces.

  • Immediate Change: firewall-cmd –add-port 4000/tcp (will not persist after reboot). This command allows temporary access before adding any rule permanently.
  • Check Configuration: Right now, you can see the configuration by typing “sudo firewall-cmd –list-all” into the shell. The output shows all active rules, services, and protocols in the default zone. Everything currently active is clearly laid out here.

Best suited for environments that require constant, non-disruptive rule updates. Firewalld can change the rules without dropping any current connections. That’s useful for production environments.

Step 6: Opening Persistent Ports and Reloading Configurations

Every time you restart, settings vanish unless you add -permanent first. That switch keeps changing, even though it’s locked in place. Skip it, configurations disappear like magic.

For example, take the HTTPS protocol and slot it into a long-term setup like this: ‘sudo firewall-cmd –permanent –add-port=443/tcp’.

  • Crucial Step: Apply your permanent configuration by reloading the firewall with the command “sudo firewall-cmd –reload”.

Without using this crucial step, your permanent configuration will not be recognized by the active runtime configuration. Inside the conf files, setup rules sit waiting. They need a reload before they turn active.

Step 7: Mastering Iptables for Advanced Packet Filtering

Enabling traffic acceptance on port 80.

Iptables is a powerful tool for granular control of network packets. It is the most customizable tool available to security administrators.

  • Basic Accept: The command is: “sudo iptables -A INPUT -p tcp –dport 80 -j ACCEPT”. This command adds a rule to the input chain that accepts all TCP traffic going to port 80.
  • IP Blocking: The command is: “iptables -I INPUT -s 198.51.100.1 -j DROP”. This method inserts the entry near the beginning, so it runs early during input processing. Position matters since entries are evaluated step by step.

The Netfilter Project provides detailed information about the official documentation. The documentation covers how the tool works and its syntax details.

Step 8: Persisting Iptables Rules Across Reboots

When the system restarts, iptables settings are lost because the Linux kernel fails to persist them automatically. Unlike UFW, those manual iptables edits need backup if stability after reboot matters. 

Rules disappear upon shutdown unless action is taken first. Saving by hand stops data loss later. Without storage, resets silently undo work. Rules run only until power drops.

On Ubuntu or Debian, the iptables-persistent package helps keep settings stable after shutdowns. It happens when you run apt-get install iptables-persistent.

When working on RHEL platforms, setting up iptables often involves the iptables-services package. Instead of relying on manual entries, that package helps keep configurations stable during shutdowns.

A key move? Triggering the save function via service management. Run the service iptables save just before exiting. That’ll save your current rules to predefined files that load at boot.

Always test rules before saving to prevent permanent lockouts. If you accidentally block SSH before saving, you can still reboot to restore access.

Step 9: Utilizing Nftables on Modern Linux Distributions

When it comes to AlmaLinux, Rocky Linux, and CloudLinux, Nftables is the preferred option over iptables. Its syntax is less complicated while delivering stronger performance. It’s handy where heavy data flow occurs.

CloudLinux homepage.

Starting differently, nftables bundles IPv4 and IPv6 controls under one interface. This setup helps users manage both older internet versions without extra hassle. For administrators handling modern networks, things move more smoothly here.

  • Configuration File: Buried in /etc/sysconfig/nftables.conf, sits the config file. Instead of digging through folders, some people tweak settings using built-in commands.

Nftables Wiki provides detailed setup info if you need it. Nftables Wiki goes beyond simple examples. Starting from fundamental concepts, it builds up to complex scenarios. The information here covers all levels without omitting key details. That’s inclusive of packet filtering.

Build Your App Now with Hostinger Horizons
Turn your idea into a powerful app in minutes with Hostinger Horizons. No coding, no hassle, just AI-powered building that brings your vision to life.
Visit Hostinger

Step 10: Standard Port Configurations for cPanel & WHM Services

PortServiceProtocolDirectionNote
21FTPTCPOutboundUse SFTP on port 22 for better security
22SSHTCPInboundEssential for WHM Transfer Tool
25SMTPTCPOutboundStandard mail sending port
53DNSTCP/UDPOutboundRequired for AutoSSL and resolution
80/443HTTP/STCPInboundWeb server traffic (443 preferred)
2082/2083cPanelTCPInbound2083 is the SSL version
2086/2087WHMTCPInbound2087 is the SSL version
3306MySQLTCPInboundOnly open if using remote databases

Configuring Your Linux VPS for a New Website or Store

After you have secured your firewall, you are ready to launch your digital presence. Hosting providers like Hostinger and IONOS are industry standards for launching a digital presence. 

Hostinger's website homepage_new 1

They offer VPS environments where firewall configuration fits neatly into their deployment workflow.

Should flexibility matter most, a WordPress setup or even a strong VPS Hosting provider might be a better fit.

  • Freelance Help: Start here if things seem too much. Platforms such as Upwork or Fiverr bring skilled workers close. They can assist with firewall tuning.
  • Marketing Tools: Once your store is live, you can always rely on Kit to handle your email marketing and user growth.

Step 11: Testing Your Opened Ports and Connectivity

Here’s something worth remembering. Check those firewall rules by testing, not just assuming.

  • Netcat (nc): Start netcat by typing ls | nc -l -p 4000 to check if things are reaching the listener. After that, test the connection again from a different terminal.
  • Telnet: Type telnet localhost 4000. This checks if the link is active. When it works, that shows the port is open and running correctly.
  • Nmap: Run nmap on your server’s IP. Check ports using ‘nmap <server_ip> -p 80’ from outside, to know what’s visible. This external perspective reveals how your firewall appears to potential attackers.

To find the latest security scanning tools, check out Nmap.org. These tools allow you to identify security holes before they can be exploited.

Nmap.org website homepage.

Security Best Practices for Enterprise-Grade Linux VPS

While running a robust firewall is essential, security best practices go beyond it.

Default Deny Policy

Start by blocking everything. With UFW, do that first. Use the following command: “sudo ufw default deny incoming.” Afterward, let outgoing traffic pass through freely. Use “sudo ufw default allow outgoing” for that setting.

This way, everything stays locked down. Nothing gets through unless someone actually opens the gate. Rules work only when they’re turned on by hand.

SSL/TLS

Send encrypted data by choosing SSL or TLS. When logging in to admin panels or accessing online tools, use HTTPS without delay.

For moving files via the web, switch to SFTP or SCP rather than relying on outdated FTP methods. Here’s a thought: block entry points for insecure protocol setups. That could help keep things tighter.

SSH Keys

Security often hides in SSH keys, not passwords, particularly when an outside port is open. When that happens, passwords become easier targets. 

Firewalls can block attacks, yet guessing still happens from time to time. SSH keys make this impossible because the hacker needs your private key.

Log Monitoring

Even though you see things in firewall records, someone still has to look at them closely. From time to time, open files like /var/log/auth.log or /var/log/messages.

Watch closely for odd entries. Inside those logs, actions that attempt to connect are clearly visible, sometimes signaling fresh breaches.

Troubleshooting Common Firewall Errors and Connectivity Issues

Setting up a firewall correctly does not always solve every connectivity issue you run into.

  • Port Closed After Config: After config, the port might be closed. Check the service using Apache or Nginx to see if it’s running and accepting connections. Use systemctl status apache2 to verify the service state before troubleshooting firewall rules.Nginx website.
  • Rules Overridden: When working with your firewall rules, it’s also important to realize that these two tools can step on each other when they’re both active. If UFW and iptables utility are both active on your system, they can behave erratically as they both attempt to configure your packet filter.
  • Syntax Errors: It’s easy to disrupt your connectivity with just one typo. When working remotely, it’s crucial to double-check all your commands before running them.
  • ISP Blocks: It’s also possible that your problem lies elsewhere. Some local Internet Service Providers block specific, commonly used ports, such as 25 for SMTP or 80 for HTTP. If you suspect that your traffic is being blocked, contact your ISP.
VPS
Cheap VPS
best option

Conclusion

A firewall is not about fear but about control. With proper rules, you can have a stable and predictable Linux VPS. This firewall configuration guide for Linux VPS ensures that your Linux VPS responds only to the rules you set and the traffic you expect.

Knowing the difference between managed and unmanaged VPS options will help you understand how much help you will need with the firewall from your hosting provider.

Next Steps: What Now?

  1. Set a recurring calendar reminder to review your firewall rules.
  2. Implement automated monitoring by installing and setting up Fail2ban
  3. Create and maintain documentation of your firewall rules. Explain why each rule exists and which service it supports.
  4. Test disaster recovery procedures.

Frequently Asked Questions

What ports should I always keep open?

Ports 22 (for SSH access) and 80/443 (for web traffic) are essential. Add others based on your specific services, but follow the principle of limited exposure.

How often should I review my firewall configuration?

Audit your rules monthly and whenever you add new services. Regular reviews help you identify unused ports and tighten security.

Best Bluehost Plan for Bloggers in 2026: An Honest Guide

Most hosting comparison articles answer the question "which plan is best for bloggers" by listing features and leaving you to figure it out. T...
6 min read
Walter Akolo
Walter Akolo
Hosting Expert

Bluehost Free Domain: How to Get One and What to Know First

A free domain is one of the most prominent features Bluehost advertises, and it genuinely is included with qualifying hosting plans. But like ...
5 min read
Walter Akolo
Walter Akolo
Hosting Expert

Handling Webhook Traffic at Scale in n8n

N8n webhook scaling breaks down faster than you'd expect. When request volumes spike, concurrency pressure builds, and executions start backin...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist

Running n8n in Production - Stability Checklist

Getting workflows live is only half the battle. n8n production stability is what keeps your automations running reliably when it actually matt...
8 min read
Christi Gorbett
Christi Gorbett
Content Marketing Specialist
Click to go to the top of the page
Go To Top
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.