VPS Tutorials
Configure UFW on a VPS: SSH access, rule order and Docker ports
Inspect UFW defaults and actual SSH listeners, allow the correct ports, manage rule order and IPv6, and understand rate limits and Docker forwarding. Includes logging, backups and lockout recovery.

A new VPS is not guaranteed to have every port open or every service installed. Check the provider firewall, host rules and actual listeners. Ubuntu images often include UFW, but its availability, defaults and enabled state depend on the image. UFW provides a simpler interface to the host's packet-filtering rules.
The goal is to allow the services you intend to publish while preserving administrative access. Prepare the policy before enabling it, and keep a working SSH session plus tested console recovery.
Do not start with enable:
sudo ufw status verbose
An unused installation may report:
Status: inactive
Inactive UFW does not prove there are no other firewall rules. Inspect existing configuration before replacing it. A common starting policy denies unsolicited incoming traffic and allows outgoing traffic; confirm or set it deliberately. Existing connections, loopback and explicitly permitted system traffic are also affected by the complete ruleset, not just the visible user list.
Allowing outgoing traffic is convenient for updates and API calls. Restrict it when your operational requirements justify the extra work, rather than assuming that every personal or production VPS needs the same policy.
First establish the actual listening SSH port:
sudo ss -lntp | grep sshd
# 或者
sudo grep -E '^Port|^#Port' /etc/ssh/sshd_config
The grep example only inspects the main file and can miss Include/Match settings or socket activation. Check listeners, the effective sshd configuration and applicable systemd socket settings. If SSH listens on 2222, allowing 22 alone does not preserve access.
Second, test the provider's VNC/serial console or rescue method. A web terminal may itself depend on SSH, so verify which recovery path you have.
Third, add and inspect required rules before activation. The original starting sequence is:
# 1. 先放行 SSH(必须在 enable 之前!)
sudo ufw allow OpenSSH
# 2. 放行 Web 端口(如果这台机器要跑网站)
sudo ufw allow 80,443/tcp
# 3. 确认规则看着对
sudo ufw show added
# 4. 启用
sudo ufw --force enable
# 5. 立刻验证状态
sudo ufw status verbose
Check the profile before using this sequence. sudo ufw allow OpenSSH uses the OpenSSH application profile; it does not dynamically read sshd's current port. Many packaged profiles contain 22/tcp, making them equivalent to a scoped form of allow 22. Run sudo ufw app info OpenSSH and explicitly allow the real port if it differs. Also set the desired default policy before enabling, for example sudo ufw default deny incoming and sudo ufw default allow outgoing, after reviewing existing requirements.
--force skips the confirmation prompt; it does not make missing access rules safe. Interactive use can retain the prompt. Immediately test a genuinely new SSH connection from another terminal before closing the original session.
# 放行单个端口(tcp 和 udp 都放行)
sudo ufw allow 8080
# 只放行 tcp
sudo ufw allow 8080/tcp
# 放行端口范围
sudo ufw allow 8000:8100/tcp
# 只允许某个 IP 访问
sudo ufw allow from 203.0.113.5 to any port 3306 proto tcp
# 允许整个网段
sudo ufw allow from 203.0.113.0/24 to any port 22
# 删除规则(两种方式)
sudo ufw delete allow 8080 # 按内容删
sudo ufw delete 3 # 按编号删
These are alternatives, not a batch to run blindly. A bare port can permit both TCP and UDP; specify the needed protocol. Replace documentation addresses and ranges with authorized sources. Do not publish a database just because an example mentions its port.
sudo ufw status numbered
[ 1] 22/tcp ALLOW IN Anywhere
[ 2] 80,443/tcp ALLOW IN Anywhere
[ 3] 22/tcp (v6) ALLOW IN Anywhere (v6)
[ 4] 80,443/tcp (v6) ALLOW IN Anywhere (v6)
With IPv6 enabled, a rule may have separate IPv4 and IPv6 entries. In this example, ufw delete 3 deletes only the numbered IPv6 SSH entry. Numbers change after deletion; display the list again before deleting another entry.
Delete the exact rule by content, such as ufw delete allow 8080, when that is the intended scope. Prefixing the original rule with delete can remove its generated IPv4/IPv6 pair:
sudo ufw delete allow 80,443/tcp # v4 和 v6 一起删
Match protocol, source and profile details. Removing a rule does not guarantee that an already established connection immediately stops or that another allow rule does not still apply.
sudo ufw deny from 203.0.113.5
sudo ufw allow from 203.0.113.5 to any port 22
For new traffic that reaches these user rules, the broad deny matches before the later SSH exception. Prefer a specific exception first:
sudo ufw allow from 203.0.113.5 to any port 22 # 先放行特定 IP
sudo ufw deny 22/tcp # 再拒绝其余的
Existing earlier rules still matter; simply appending this pair may not fix the policy. Review the complete numbered order and use an intentional insertion position when necessary. UFW also has before/after and connection-state rules, so the first matching user rule is not the whole packet path.
sudo ufw limit ssh
Use an explicit actual SSH port/protocol when needed. The documented limit normally allows traffic but denies connections when a source attempts to initiate 6 or more connections within 30 seconds. It is a connection-rate mechanism, not an authentication log analyzer or permanent ban. A preceding allow can bypass it, and users behind a shared NAT can affect each other.
Fail2Ban reads service logs and has different behavior. Both can be useful, but assess interactions and automatic reconnect workloads. If limit blocks legitimate work, inspect sudo ufw status numbered and adjust the responsible rule through retained access. sudo ufw disable temporarily disables UFW entirely, exposing other services; use console recovery or a narrowly scoped correction when possible. Fail2Ban self-lockout recovery describes that separate mechanism.
# 看有哪些可用的配置
sudo ufw app list
# 看某个配置的详情(用了哪些端口)
sudo ufw app info 'Nginx Full'
# 直接按名字放行
sudo ufw allow 'Nginx Full'
sudo ufw allow 'Nginx HTTP'
| Profile | Typical packaged ports; verify locally |
|---|---|
OpenSSH | 22/tcp, not automatically the effective sshd port |
Nginx HTTP | 80/tcp |
Nginx HTTPS | 443/tcp |
Nginx Full | 80 and 443/tcp |
Apache Full | 80 and 443/tcp |
Profiles are INI files under /etc/ufw/applications.d/. Nginx Full is commonly installed with a distribution's Nginx package; container or custom installations need not provide it. Review profile contents after changes instead of assuming service configuration and firewall profiles stay synchronized.
Inspect /etc/default/ufw:
IPV6=yes
For a dual-stack service, keep yes and verify both rule families. no changes IPv6 handling; it is not a reliable way to declare IPv6 irrelevant. UFW's behavior and existing backend rules must be checked, and other firewall managers can change the result. Test from an external IPv6 client as well as IPv4. See IPv6 VPS setup.
Docker creates NAT and forwarding rules, commonly through nat and filter. Published container traffic can traverse forwarding chains rather than UFW's ordinary host INPUT rules. The backend and Docker version matter; verify real reachability.
# docker-compose.yml
services:
db:
ports:
- "3306:3306" # ❌ 这个端口会直接暴露到公网,UFW 拦不住
The unqualified mapping, like docker run -p 3306:3306, normally publishes on host interfaces. A missing UFW incoming allow for 3306 is not enough to conclude the database is private.
If only another container needs the database, omit host ports and use the private container network. If a host tool or SSH tunnel needs it:
ports:
- "127.0.0.1:3306:3306" # ✅ 只监听本机,公网访问不到
Keep Docker supported and verify from an external host; a loopback listener is also reachable by trusted host processes. Use an authenticated SSH tunnel for remote administration and review database exposure boundaries. Public reverse-proxy ports should remain deliberately public; not every container port belongs on loopback.
Community tools such as ufw-docker / ufw-docker integrate Docker forwarding with UFW, commonly using DOCKER-USER on an iptables backend. Review the actual rules, trusted-source exceptions and compatibility. Docker's native nftables backend needs its applicable forwarding mechanism; do not assume it exposes an identical DOCKER-USER chain. Recheck after network or Docker upgrades.
The original illustration is:
// /etc/docker/daemon.json
{ "iptables": false }
It is not valid JSON with the displayed comment, and it is not a recommended configuration. Disabling rule creation can break networking/NAT and requires you to own the complete policy. Prefer deliberate publication, often 127.0.0.1: for administrative listeners, plus tested forwarding controls where needed.
The following is a limited illustration, not a complete production policy:
# 如果真要限制出站(先想清楚,很容易把自己锁死)
sudo ufw default deny outgoing
sudo ufw allow out 53 # DNS
sudo ufw allow out 80,443/tcp # HTTP/HTTPS
sudo ufw allow out 123/udp # NTP
DNS, HTTP/HTTPS and NTP are only some dependencies. You may also need mail, monitoring, remote SSH, backup destinations, application ports and IPv6. Test name resolution and real operations from the host and containers. An outgoing mistake can leave inbound SSH working while apt update and API calls time out.
Check the current logging level rather than assuming it is disabled:
sudo ufw logging on # 开启
sudo ufw logging medium # 调整级别:off/low/medium/high/full
Depending on logging services, events appear in /var/log/ufw.log, /var/log/syslog or the kernel journal:
sudo tail -f /var/log/ufw.log
medium may help during diagnosis. low generally rate-limits blocked-event logging; medium adds more activity, while high and full can create large volumes. Choose the least noisy level that answers the question and configure rotation; see VPS disk cleanup.
Repeated UFW BLOCK events often reflect scans. A blocked destination port does not prove a service is listening there. Correlate source, destination, actual listeners and business impact.
| File | Purpose |
|---|---|
/etc/ufw/user.rules | IPv4 user rules managed by ufw |
/etc/ufw/user6.rules | IPv6 user rules |
/etc/default/ufw | Defaults and IPv6 setting |
/etc/ufw/applications.d/ | Application profiles |
/etc/ufw/before.rules | Before rules for custom policy |
Prefer the CLI for user.rules; ufw manages that file and concurrent/manual edits are easy to mishandle. Use before.rules or after.rules for deliberately designed custom rules. Back up before changes:
sudo cp -r /etc/ufw /root/ufw-backup-$(date +%F)
Also preserve /etc/default/ufw and relevant provider settings; the displayed copy covers only the UFW directory. Protect backups and document a recovery method.
SSH fails after enabling UFW: if the original session remains, the source's repair example is:
sudo ufw allow OpenSSH
sudo ufw reload
It only helps if OpenSSH includes the actual port. Add the required explicit port/source rule instead when necessary. With no SSH access, use console or rescue; see UFW SSH lockout recovery.
Ping works but the website does not: ICMP reachability does not prove TCP 80/443 or the actual application port is reachable. Check service listeners, proxy, provider firewall and host/forwarding rules. See a running service inaccessible externally.
A rule exists but the port is still closed:
sudo ufw status numbered # 1. 规则在不在、顺序对不对
sudo ss -lntp 'sport = :8080' # 2. 服务真的在监听吗
sudo ufw show raw | head -30 # 3. 看底层 iptables 链
Check the service before blaming the firewall. A listener on 127.0.0.1 is intentionally local. The abbreviated raw output is only a starting point, not the complete policy. See port conflicts.
Docker traffic bypasses an incoming rule: inspect the forwarding/publication path above. 127.0.0.1 is suitable for a listener intended only for host administration.
SSH was moved to another port: OpenSSH is a static profile, not a live sshd query. The original sequence is:
sudo ufw allow 2222/tcp
sudo ufw delete allow OpenSSH
sudo ufw reload
Add and test the real new port before deleting the old permission. Check what deleting the profile actually removes, including IPv6. CLI rule changes normally take effect immediately; an extra reload is not required for each allow/delete.
Active status with no visible user rules: ufw status does not show every before/after or foreign rule. If defaults deny incoming, an old tracked SSH connection may survive while a new one fails. Add and test the required administrative rule immediately.
-
sudo ufw status verbosereportsStatus: activewith the intended rules. - The deliberate starting policy is
deny (incoming), allow (outgoing), or an explicitly justified alternative. - The real SSH port is allowed;
OpenSSHhas been inspected if used. - Required web ports 80/443 are allowed.
- A separate fresh SSH connection succeeds.
- Internal listeners use private networking or
127.0.0.1; mappings such as-p 3306:3306have been reviewed. -
IPV6=yesand external IPv6 reachability match the intended policy. - Logging and retention are appropriate.
-
/etc/ufw, defaults and recovery instructions are backed up.
How does UFW relate to iptables? It is a simpler frontend that loads filtering rules through the distribution's backend, often iptables using nft compatibility. Complex forwarding or state policies may require custom rules and backend-specific review.
Can it run alongside firewalld? Avoid having two managers own the same host rules. Use one deliberate owner and review distribution conventions; see choosing a VPS distribution.
Do rule changes need reload? ufw allow/delete normally applies immediately when enabled. ufw reload is relevant after supported direct changes under /etc/ufw/ or other configuration work; validate through retained access.
Does disable delete rules? ufw disable stops applying UFW while retaining saved rules for enable. sudo ufw reset resets configuration and is a deliberate rebuild operation; inspect its effects before using it.
Do provider security groups replace UFW? They are separate enforcement layers. Check both, plus any container forwarding rules, when a port fails.
Does changing port 22 secure SSH? It mainly reduces scanner noise. Use SSH key authentication and a tested access policy.
Can UFW stop DDoS? Local filtering can reduce some unwanted processing, but cannot restore upstream bandwidth already saturated. Volumetric protection belongs upstream; application attacks also need application-aware controls. See website request-flood mitigation.