Skip to content

Instantly share code, notes, and snippets.

@wittawasw
Created March 10, 2026 06:22
Show Gist options
  • Select an option

  • Save wittawasw/7d4a8dd0073ae55ad61952b211fd219d to your computer and use it in GitHub Desktop.

Select an option

Save wittawasw/7d4a8dd0073ae55ad61952b211fd219d to your computer and use it in GitHub Desktop.
Setup UFW for app instance with Cloudflare DNS
#!/usr/bin/env bash
set -e
# Allow only Cloudflare to access HTTP/HTTPS using UFW
CF_IPV4_URL="https://www.cloudflare.com/ips-v4"
CF_IPV6_URL="https://www.cloudflare.com/ips-v6"
SSH_PORT=22
echo "Installing ufw if missing..."
apt-get update -y
apt-get install -y ufw curl
echo "Resetting firewall rules..."
ufw --force reset
echo "Setting default policies..."
ufw default deny incoming
ufw default allow outgoing
echo "Allowing SSH..."
ufw allow ${SSH_PORT}/tcp
echo "Fetching Cloudflare IPv4 ranges..."
for ip in $(curl -s $CF_IPV4_URL); do
ufw allow proto tcp from $ip to any port 80 comment 'Cloudflare HTTP'
ufw allow proto tcp from $ip to any port 443 comment 'Cloudflare HTTPS'
done
echo "Fetching Cloudflare IPv6 ranges..."
for ip in $(curl -s $CF_IPV6_URL); do
ufw allow proto tcp from $ip to any port 80 comment 'Cloudflare HTTP'
ufw allow proto tcp from $ip to any port 443 comment 'Cloudflare HTTPS'
done
echo "Enabling firewall..."
ufw --force enable
echo "Firewall rules applied. Current status:"
ufw status numbered
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment