Secure Your Server: Configure Linux Firewall Rules via the CLI
Take control of your servers network security by learning how to configure Linux firewall rules via the CLI. This practical guide walks through real commands, distribution-specific notes, and fail-safe testing so you can secure services without risking remote lockout.
Managing network access is a foundational task for any server operator. When you run services on a VPS — whether for a small website, a corporate application, or a development environment — a properly configured firewall dramatically reduces attack surface and helps maintain uptime. This article walks through practical, command-line-focused strategies for configuring Linux firewall rules, with implementation details, examples, and guidance for different distributions and use cases.
Why CLI Firewall Configuration Matters
While graphical tools can be convenient, the CLI offers several advantages for server administration: repeatability, automation, minimal dependencies, and the ability to work over low-bandwidth connections (SSH). On remote VPS instances, where you may not have a control panel or want to use configuration management tools (Ansible, Puppet), knowing how to craft and apply firewall rules from the command line is essential.
Core Principles
Before jumping into commands, keep these core principles in mind:
- Default-deny posture: Deny all incoming traffic by default and only allow necessary services.
- Stateful filtering: Use connection tracking to allow established/related traffic while denying new unsolicited connections.
- Least privilege: Only open the minimal set of ports/protocols required for the service.
- Persistence and reproducibility: Save and version your rule sets so you can restore or redeploy reliably.
- Testing and fail-safe access: Have a recovery mechanism (console access or scheduled rollback) in case you lock yourself out.
Understanding the Linux Firewall Stack
Linux has evolved from iptables to nftables as the preferred packet filtering framework; many distributions still expose higher-level tools like ufw or firewalld. Knowing how they relate helps you choose the right approach:
- nftables — modern packet-filtering utility; replaces iptables with a unified syntax and better performance.
- iptables — widely used legacy tool; still present on many systems and supported by wrappers.
- ufw (Uncomplicated Firewall) — user-friendly frontend for iptables/nftables on Debian/Ubuntu.
- firewalld — daemon-based manager used on RHEL/CentOS/Fedora; offers zones and rich rules and can use nftables backend.
When to use each
- Use nftables for new deployments where you want minimal complexity and modern features.
- Use iptables if you maintain legacy systems or rely on tooling that expects iptables.
- Use ufw for quick, readable rules on Ubuntu/Debian VPS when you want simplicity.
- Use firewalld when you need zone-based management on CentOS/RHEL and system-integrated controls.
Practical CLI Examples and Patterns
Below are concrete, battle-tested patterns you can apply. Replace port numbers, interfaces, and subnets with values applicable to your environment.
1) Baseline: Allow SSH, deny others (nftables)
Create a minimal nftables config that defaults to drop and allows SSH with connection tracking:
sudo nft add table inet filter
sudo nft 'add chain inet filter input { type filter hook input priority 0; policy drop; }'
sudo nft add rule inet filter input ct state established,related accept
sudo nft add rule inet filter input iif lo accept
sudo nft add rule inet filter input tcp dport 22 ct state new limit rate 3/minute accept
sudo nft add rule inet filter input ip protocol icmp icmp type echo-request accept
Save the rules (Debian/Ubuntu): sudo nft list ruleset > /etc/nftables.conf and enable persistence via systemd or distro-specific service.
2) SSH hardening
- Use a non-standard port (e.g., 2222) and restrict to known IPs if possible:
nft add rule inet filter input tcp dport 2222 ip saddr 203.0.113.0/24 accept - Enable rate limiting to mitigate brute force:
limit rate 3/minuteas shown above. - Combine firewall rules with SSH config: disable password auth, use key-based auth, and allow only Protocol 2.
3) Service allow rules (ufw examples)
On Ubuntu, ufw is straightforward:
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow from 198.51.100.0/24 to any port 3306
sudo ufw enable
Use ufw status verbose to audit rules.
4) Complex setups: Firewalld zones and rich rules
Firewalld offers zones which match interfaces or sources. Example: put public-facing interface in public zone and database interface in internal zone:
sudo firewall-cmd --permanent --zone=public --add-service=http
sudo firewall-cmd --permanent --zone=internal --add-source=10.0.0.0/24
sudo firewall-cmd --reload
5) Logging and monitoring
Add logging rules to nftables or iptables to capture denied traffic for analysis — but be careful to avoid log flooding:
sudo nft add rule inet filter input ct state invalid counter log prefix "DROP_INVALID: " limit rate 5/minute drop
Use tools like journalctl, rsyslog or centralized logging (ELK, Graylog) to aggregate and analyze logs.
Application Scenarios
Small business web server
Typical needs: HTTP/HTTPS, SSH for management, and possibly SMTP. Recommended approach:
- Default deny incoming, allow 80 and 443, limit access to management ports with IP restrictions.
- Use a reverse proxy or web application firewall (WAF) for application-layer protection.
- Harden SSH and use key-based auth with limited sudo privileges.
Database server in a private subnet
Keep the database port accessible only from application servers. Use nftables or firewalld to enforce source-based rules:
sudo nft add rule inet filter input tcp dport 3306 ip saddr 10.0.0.0/24 accept
This prevents exposure to the public internet while allowing internal communications.
CI/CD runner or developer VPS
Developers often need ephemeral access and services. Use a jump host or VPN and restrict the runner host to only accept traffic from the CI system or over the VPN. Avoid opening build agents directly to the internet.
Advantages and Trade-offs
Choosing the right firewall solution depends on operational constraints. Below is a concise comparison.
- nftables — Pros: performant, expressive, single API for IPv4/IPv6/ARP. Cons: newer ecosystem, less familiar to some admins.
- iptables — Pros: mature tooling and documentation. Cons: multiple frontends (iptables, ip6tables) and complexity.
- ufw — Pros: simple, easy to maintain. Cons: less flexible for complex setups.
- firewalld — Pros: dynamic rulesets, zones, integration with network managers. Cons: can be complex and opaque when troubleshooting.
For high-performance, large-scale environments, nftables usually offers the best path forward. For small and medium setups where simplicity matters, ufw or firewalld provide a faster route to secure defaults.
Operational Best Practices and Hardening Checklist
- Backup your rules: Keep copies of rule files in version control and remote backups.
- Use a test window: Apply critical changes during maintenance windows and have an automated rollback (e.g., a cron job that restores previous rules after X minutes unless confirmed).
- Monitor connectivity: Use automated checks to detect accidental lockouts and alert you via out-of-band channels.
- Log selectively: Log suspicious drops but avoid logging benign high-volume traffic to prevent storage exhaustion.
- Combine layers: Use host firewall + cloud/VPS provider network controls (security groups) for defense-in-depth.
- Automate: Manage firewall state with Ansible or scripts to ensure consistency across multiple VPS instances.
Choosing a VPS for Secure Deployments
When picking a VPS provider, consider whether the provider offers features that complement your firewall strategy: private networking, network isolation, snapshots, console access, and DDoS protection. For many US-based deployments aimed at performance and low-latency access to North American users, a reliable USA VPS can reduce latency while offering sufficient control over networking.
For example, see available options here: USA VPS.
Conclusion
Securing a Linux server via the CLI is both practical and powerful. By following a default-deny posture, using stateful filtering, restricting management access, and employing persistence and logging, you can build a robust network defense for a wide variety of deployment scenarios. Whether you choose nftables for modern performance or ufw/firewalld for ease of use, the key is to apply consistent, auditable rules and to integrate host-level firewalling with your VPS provider’s network controls.
When provisioning infrastructure, select a VPS that supports out-of-band recovery and private networking so your firewall strategy can be safely applied and tested. For US-based deployments and a variety of instance types, explore the USA VPS offerings: https://vps.do/usa/.