Setup Firewall on Linux



This content originally appeared on DEV Community and was authored by MUHAMMAD ARBAB ANJUM

Let’s secure the server with firewall:

sudo apt install ufw
sudo ufw status
sudo ufw enable

This will enable the firewall and allow all incoming and outgoing traffic. To allow incoming traffic on a specific port

Allow Inbound:

sudo ufw allow 22
sudo ufw allow 22,80,443 #allow multiple ports
sudo ufw allow 8000:9000/tcp #allow port range
sudo ufw allow from 192.168.1.100 #allow specific IP
sudo ufw allow from 192.168.1.100 to any port 22 #restrict to a port
sudo ufw allow HTTP #allow HTTP
sudo ufw allow https #allow HTTPS

Deny Inbound

sudo ufw deny 21 #deny port
sudo ufw deny out to 10.0.0.5 #deny to an IP

Allow Outbound

sudo ufw default allow outgoing #allow all
sudo ufw allow out 443 #on specific port
sudo ufw allow out to 1.1.1.1 #allow specific IP

Check Rules

sudo ufw status numbered
sudo ufw delete 3 #Delete rule number 3
sudo ufw reset #reset all rules

Example: NodeJs App running with Local DB

sudo ufw allow 22/tcp
sudo ufw allow from your_ip to any port 22 #limit SSH to your IP
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw allow 3000/tcp
sudo ufw deny 5432/tcp  #PostgreSQL (Port 5432): Explicitly block external access

PostgreSQL should already bind to 127.0.0.1 (check /etc/postgresql/…/postgresql.conf):

listen_addresses = 'localhost'  #Ensures DB is not exposed externally

Other ports allow (If necessary):

Allow HTTP/HTTPS

sudo ufw allow out 80/tcp
sudo ufw allow out 443/tcp

Allow SMTP (If sending emails)

sudo ufw allow out 25/tcp
sudo ufw allow out 587/tcp  # For TLS

Allow NTP (For time sync)

sudo ufw allow out 123/udp

Block All Other Outbound

If you want strict outbound control, first allow what’s needed, then:

sudo ufw default deny outgoing

Enable UFW & Verify Rules

sudo ufw enable
sudo ufw status verbose

Protection against brute-force

sudo apt install fail2ban
sudo systemctl enable fail2ban

Configuration for fail2ban

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local
[DEFAULT]
# Ban IPs for 1 hour (3600 seconds)
bantime = 3600
# Maximum retries before ban
maxretry = 5
# Time window for maxretry
findtime = 600
# Ban IPs on all ports (not just the attacked service)
banaction = ufw
# Whitelist your own IP (replace `your_ip`)
ignoreip = 127.0.0.1/8 ::1 your_ip


This content originally appeared on DEV Community and was authored by MUHAMMAD ARBAB ANJUM