How to set up a basic firewall on Ubuntu with UFW

Redes & Segurança · By · Published on · Updated on · 7 min read

Close-up blurred snippet of colorful code on a monitor
Close-up of code on a monitor with a technical look, suitable for tutorials and articles Photo: Godfrey Atima / Pexels

This step-by-step guide shows how to configure a basic, secure firewall on Ubuntu using UFW. You’ll set default policies, open only the services you need, enable logging, and verify everything is working. It applies to both servers and desktops. sudo access is required. If you manage the system remotely via SSH, open the SSH port before enabling the firewall to avoid losing access.

Prerequisites and what UFW is

UFW (Uncomplicated Firewall) is a simple layer to manage network rules on Ubuntu. It controls the kernel’s filtering mechanism and makes common tasks—like allowing or denying ports and IPs—easier.

A basic firewall typically follows two principles: deny incoming connections by default and allow outgoing connections. This exposes only what you explicitly need and reduces the attack surface.

To follow this guide you need sudo access, a terminal, and knowledge of which ports/services your system must expose (SSH, HTTP, databases, etc.).

  • Sudo access on the Ubuntu host
  • A list of services that must be reachable
  • IP addresses or networks that should be allowed (if you will restrict access)

1. Install and check initial status

On many Ubuntu installs UFW is already available. Still, confirm it’s installed and check the current status. The status command doesn’t change rules; it only shows the current configuration.

If status shows “inactive”, the firewall isn’t applied yet. We’ll configure rules first and enable it afterward to avoid accidentally locking out remote access.

sudo apt update
sudo apt install -y ufw

# Verifique versão e status atual
sudo ufw --version
sudo ufw status verbose

2. Set secure default policies

The first step is to enforce secure default policies: deny all incoming and allow all outgoing. This blocks accidentally exposed services while keeping outbound access for updates, repositories, and integrations.

If you need different defaults later, adjust them after explicitly allowing the required services.

sudo ufw default deny incoming
sudo ufw default allow outgoing

3. Ensure remote access (SSH) before enabling

If you manage the system via SSH, allow SSH before enabling UFW. Ignoring this step can terminate your session and prevent future remote access.

Use the application profile name when available (OpenSSH) or specify the port. If you use a nonstandard port, adjust the number accordingly.

# Se o serviço OpenSSH está instalado:
sudo ufw allow OpenSSH

# OU, especificando a porta diretamente (padrão 22):
# sudo ufw allow 22/tcp

# Porta SSH não padrão (exemplo):
# sudo ufw allow 2222/tcp

4. Allow essential services with least privilege

Now allow only the services your system actually needs to expose. For most web servers that means HTTP and HTTPS. Internal databases should usually be restricted to the application IP or a specific network.

Whenever possible, restrict access by IP or network. This lowers the risk of exploitation by unknown hosts.

  • HTTP: 80/tcp
  • HTTPS: 443/tcp
  • DNS (if your host provides DNS to others): 53/udp
  • NTP (time server): 123/udp
  • Databases/internal apps: allow only trusted IPs or networks
# Web (HTTP/HTTPS)
sudo ufw allow 80,443/tcp

# DNS (apenas se este host atende requisições DNS)
sudo ufw allow 53/udp

# Exemplo: liberar PostgreSQL apenas para o IP da aplicação
sudo ufw allow from 203.0.113.10 to any port 5432 proto tcp

# Restringir SSH à sua rede corporativa (exemplo)
sudo ufw allow from 192.0.2.0/24 to any port 22 proto tcp

# Bloquear explicitamente um serviço que não deve receber conexões (ex.: SMTP)
sudo ufw deny 25/tcp

5. Enable the firewall and review rules

With default policies set and essential rules allowed, enable UFW. From this point on, connections are filtered according to your rules.

Use the numbered listing to review rules and, if needed, remove rules by number later. After making changes, reload UFW to apply them without disabling the firewall.

sudo ufw enable

# Revise as regras ativas (numeradas)
sudo ufw status numbered

# Após ajustes de regras, recarregue
sudo ufw reload

6. Enable logging and set verbosity

Enable event logging to help with auditing and troubleshooting. UFW logs are usually available at /var/log/ufw.log via the system logging on Ubuntu.

Levels like low, medium, and high control how much detail is recorded. Adjust according to your needs and monitor log growth.

  • low: essential events
  • medium: good balance between visibility and noise
  • high: very verbose; use sparingly in production
# Ativar logs e definir nível sugerido
sudo ufw logging on
sudo ufw logging medium

Verification and common troubleshooting

Validate from another host that the expected ports are open and others are closed. At the same time, watch the log while testing to confirm rules are allowing or blocking as intended.

Common issues and how to think about them:

- Remote connection dropped after enabling: check that the access port/service was allowed correctly and that any IP restrictions include your current address.

- Service doesn’t respond even though allowed: confirm the process is listening on the expected port/interface and using the correct protocol (tcp/udp).

- Docker and port mapping: containers can create their own rules. Only publish what’s necessary and test the host’s actual exposure.

- IPv6: if your host uses IPv6, ensure it’s enabled in UFW and that rules cover both protocols.

# Testes a partir de outro host da rede/Internet
nmap -Pn -p 22,80,443 SEU_IP
nc -vz SEU_IP 22

# No servidor, acompanhe logs e confira regras
sudo tail -n 50 /var/log/ufw.log
sudo ufw status numbered

# Se necessário, remova uma regra pelo número
# sudo ufw delete NUMERO

# Último recurso para voltar ao padrão (cautela)
# sudo ufw reset

Frequently asked questions

Does UFW replace iptables or nftables?

UFW is a convenience layer that manages rules for the kernel’s filtering mechanism. It simplifies day-to-day administration without requiring low-level commands. You still rely on the kernel’s protection, but with a more direct interface to allow, deny, and review rules.

Do UFW rules persist after a reboot?

Yes. Once enabled, UFW loads its rules automatically on boot. If you change critical logging or network configurations, review the status and rules after reboot to ensure everything remains as expected.

How should I handle Docker and UFW on the same host?

Containers can create their own rules when publishing ports, which may affect expected behavior. Plan Docker port exposure carefully and test from another host. Restrict services to specific interfaces and publish only what’s necessary to avoid unintended exposure.

Can I allow a range of ports with UFW?

Yes. You can allow a port range by specifying the range and protocol. This is useful for applications that require multiple adjacent ports. Still, prefer to open the minimum required ports and restrict by IP or network when possible.

How do I enable IPv6 in UFW?

If your environment uses IPv6, edit the UFW configuration to enable IPv6 support and then reload the firewall to apply changes. Also create rules that cover both IPv4 and IPv6 traffic for the services you expose.

Can I apply rules to a specific network interface (e.g., eth0)?

Yes. Rules can target specific interfaces for additional granularity. This is useful when a host has multiple NICs or networks (public and private). Plan carefully to avoid blocking administrative access or exposing services on the wrong interface.

Want a second opinion on your UFW rules?

If you need help reviewing open ports, tightening policies, or improving logging, describe your services and we’ll outline a hardening checklist tailored to your setup.

Talk about Ubuntu firewall

See also