You can restrict VPS incoming connections within your VPS provider’s admin page (at a network-level), but if you can’t restrict outgoing connections, or you prefer to use a firewall at a server-level. you can use ufw.

Table of Contents

Introduction

This is an example of how ufw works.

You may need to start and enable ufw service. You need to be a root user or use sudo to run these commands.

Rules

Add default rules:

ufw default deny incoming
ufw default allow outgoing

Allow from IP:

ufw allow from 125.250.25.250

To allow a specific port:

ufw allow 1050/tcp

Allow http in:

ufw allow in http
  • For services included in /etc/services, you can use the service name (http) instead of the port number (80) and protocol (tcp).

Rate limit (to 6 connections in 30 seconds):

ufw limit 22/tcp

Full syntax example:

ufw deny proto udp comment 'restrict udp'

Application profiles

Some applications create rules for UFW that you can use. For example, OpenSSH creates rules to open port 22/TCP. To list these application profiles, run:

ufw app list

Get more info about an application profile with:

ufw app info <profile name>
# e.g.: ufw app info OpenSSH

You can add one of these profiles in a similar way to adding regular rules:

ufw allow OpenSSH

Enable the firewall

Enable firewall:

ufw enable

Check rules and their number (only if firewall is enabled):

ufw status numbered

More options

Insert a rule at a specific position:

ufw insert <NUMBER> <RULE>

Disable the firewall:

ufw disable

Docker

If you use Docker, -p flag makes the selected port available to everyone regardless of your ufw configuration, so you need to use --network host instead.

docker run -d --network host nginx

You may also need to change default rule for routed traffic:

ufw default allow routed

If you have any suggestion, feel free to contact me via social media or email.