Set up UFW or iptables to control network traffic to your server.
UFW is the recommended firewall for Ubuntu/Debian servers.
# Install UFW
apt install ufw -y
# Set default policies
ufw default deny incoming
ufw default allow outgoing
# Allow SSH (important — do this before enabling!)
ufw allow OpenSSH
# Enable the firewall
ufw enable
# Install UFW
apt install ufw -y
# Set default policies
ufw default deny incoming
ufw default allow outgoing
# Allow SSH (important — do this before enabling!)
ufw allow OpenSSH
# Enable the firewall
ufw enable
# Allow HTTP and HTTPS
ufw allow 80/tcp
ufw allow 443/tcp
# Allow specific port
ufw allow 3306/tcp # MySQL
# Allow from specific IP
ufw allow from 192.168.1.100
# Allow port range
ufw allow 8000:8100/tcp
# Delete a rule
ufw delete allow 3306/tcp
# Check status
ufw status verbose
# Allow HTTP and HTTPS
ufw allow 80/tcp
ufw allow 443/tcp
# Allow specific port
ufw allow 3306/tcp # MySQL
# Allow from specific IP
ufw allow from 192.168.1.100
# Allow port range
ufw allow 8000:8100/tcp
# Delete a rule
ufw delete allow 3306/tcp
# Check status
ufw status verbose
# List available profiles
ufw app list
# Allow Nginx
ufw allow 'Nginx Full'
# Allow specific profile
ufw allow 'OpenSSH'
# List available profiles
ufw app list
# Allow Nginx
ufw allow 'Nginx Full'
# Allow specific profile
ufw allow 'OpenSSH'
For more granular control:
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Drop all other incoming
iptables -A INPUT -j DROP
# Save rules
iptables-save > /etc/iptables/rules.v4
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Drop all other incoming
iptables -A INPUT -j DROP
# Save rules
iptables-save > /etc/iptables/rules.v4