Network Ports and Firewalls
Learn how TCP and UDP ports, listening sockets, and firewall rules shape backend reachability, with practical examples for safer production deployments.
Reachability depends on a listening service, a working route, and rules that allow traffic in both directions. This guide explains TCP and UDP ports, host and network firewalls, and a narrow UFW setup, then works through timeouts, blocked egress, and failed health checks. Use the checklist to trace a connection from the client and restrict exposed services to approved sources.
Network Ports and Firewalls
Introduction
When a service will not connect, an open port is only one part of the story. The process must listen on the right address, routing must work, and the response must get back to the client.
This guide traces that path across host and network firewalls. It also shows a narrow UFW rule and covers common causes of timeouts, failed health checks, and blocked egress.
Where firewalls fit
Host firewalls filter traffic on the server; network firewalls, security groups, and ACLs filter at a boundary. Stateful rules track connections; stateless rules may need return-path rules. Traffic also needs a route and listener.
flowchart LR
C[Client] --> N[Network firewall]
N --> L[Load balancer]
L --> H[Host firewall]
H --> S[Service listening on TCP 8080]
S -->|response| H
H --> L
L --> C
S -->|outbound dependency call| E[External service]
Inbound rules govern arriving traffic; outbound rules govern traffic leaving. A web tier might accept public HTTPS at a load balancer and allow application traffic only from that balancer. Egress may need DNS, telemetry, updates, or specific APIs. Many cloud environments allow outbound traffic by default, so inspect the effective policy.
Proxies and load balancers do different work: firewalls permit or block network flows, proxies relay application connections, and load balancers select backends. Application controls do not replace network segmentation. See load balancing and cloud security.
Stateful and stateless firewall rules
A stateful firewall tracks an allowed flow and can permit reply packets that belong to it. For example, after allowing a client to connect to TCP port 443, it can recognize the server’s response without a separate inbound rule for the client’s temporary source port.
A stateless filter evaluates each packet on its own. It needs rules in both directions: one for the request to the server port and another for the response to the client’s address and ephemeral port. A missing return rule can look like a timeout even when the request reaches the server. Keep return rules scoped to the expected peers, protocol, and port range; do not open every ephemeral port to every source.
State tracking is a useful policy mechanism, not a substitute for explicit access decisions. Confirm which device is stateful or stateless on the path, and inspect its effective rules and flow logs when a connection behaves differently in each direction.
When to use ports and firewall rules
Use explicit listener and firewall configuration when a service crosses a trust boundary, such as an API exposed publicly or an admin endpoint. A local process may need only loopback. Identify a port’s owner and clients before opening it. See the backend engineering roadmap for related topics.
Ubuntu 24.04 with UFW
UFW is Ubuntu’s simpler interface for configuring the Linux Netfilter firewall. It tracks connections, so reply packets for an allowed connection do not need a second broad inbound rule. A new inbound connection still needs an explicit allow rule.
The example below permits TCP port 8443 only from one administrator or test client. 198.51.100.42 is a documentation address; replace it with the actual approved source before applying the rule. These commands assume UFW is already active. If you are connected over SSH, confirm that your current address has an allowed rule and that you have console access before changing firewall policy.
# Confirm UFW is active and a service is listening on this port.
sudo ufw status verbose
sudo ss -lntp 'sport = :8443'
# Preview, then add the narrow inbound rule.
sudo ufw --dry-run allow in from 198.51.100.42 to any port 8443 proto tcp
sudo ufw allow in from 198.51.100.42 to any port 8443 proto tcp
sudo ufw status numbered
# From the approved client, test TCP reachability.
nc -vz -w 3 server.example 8443
# Remove the rule if the test fails or access is no longer needed.
sudo ufw delete allow in from 198.51.100.42 to any port 8443 proto tcp
Use the service’s real hostname in the test. A successful TCP connection confirms reachability to a listener, not that TLS or the application works. Opening a port also provides no authentication or authorization; the service still needs its own access controls.
UFW is not interchangeable with direct nftables rules or cloud firewalls. On Ubuntu, UFW manages host rules through Netfilter; nftables is the lower-level rule system. Cloud controls run at different boundaries. For example, AWS Security Groups filter traffic for an instance and track connections, while VPC network ACLs filter at subnet boundaries and are stateless. A subnet ACL therefore needs explicit rules for return traffic. Check the provider’s documentation and inspect each layer separately; the syntax and behavior vary by platform (AWS VPC security controls).
For a private service, bind to its private interface or container network and allow its port only from the load balancer’s identity or subnet. Keep debug ports such as 9229 private. Store rules in reviewed infrastructure configuration and test the policy in staging.
Production failure scenarios
Clients time out despite an open rule. The process may be stopped, bound to loopback, or blocked at another boundary. Check the listener, then inspect effective cloud and host rules before adding exceptions.
A subnet change breaks deployment. Rules tied to old addresses can strand a service. Prefer stable security-group references and review routes with firewall policy.
The API cannot reach a dependency. Egress restrictions, DNS, or a missing return route can break calls while inbound checks stay green. Document required destinations and alert on connection and DNS errors.
Backends fail health checks. The check may use a different port or source range. Allow the documented health-check path, verify the binding, and monitor health status with host logs. Silent drops often appear as timeouts.
An emergency allow rule stays after the incident. A temporary source range may become permanent and widen access long after the repair. Record an owner and review date when adding an exception, then remove it when the approved need ends.
Trade-off table
| Policy | Benefit | Cost |
|---|---|---|
| Allow all inbound | Simple for a short-lived local experiment | Exposes unintended listeners and is unsuitable for production |
| Allow required ports from any source | Easy public service setup | Makes every permitted service reachable by any routable client |
| Allow required ports from trusted sources | Limits exposure and supports clear trust boundaries | Requires maintaining source identities and health-check paths |
| Deny outbound by default | Limits exfiltration and unexpected dependencies | Needs an accurate egress inventory and can break DNS, updates, or telemetry |
| Manage rules as reviewed configuration | Makes policy changes repeatable and traceable | Requires a rollout and rollback path for urgent changes |
Choose the narrowest working policy and verify both directions.
Observability checklist
- Record listener state at deploy time; alert when sockets disappear.
- Retain rule changes and flow logs with timestamps and source/destination addresses.
- Track timeouts, refusals, load balancer health, DNS, and dependency errors separately.
- Test from the client network; a local request does not prove external reachability.
- Include protocol and port in incident notes and correlate with application logs.
Security and compliance notes
Expose only needed ports. Restrict administration to a VPN or management network and use encrypted protocols. Review IPv4 and IPv6 separately, and treat container port publishing as an exposure decision. A port scan shows reachability from one vantage point; it does not prove which application is behind the port.
Apply rules only to systems and networks you are authorized to administer. Before scanning or testing reachability, get approval from the system owner and keep activity within the agreed scope. Prefer narrow sources, destinations, protocols, and ports; record the service owner, reason, and review date for exceptions.
Firewall changes and flow logs can reveal addresses, service relationships, and user activity. Limit access to people who need that information, retain it according to operational and compliance policy, and record approvals for rule changes.
Quick recap checklist
- Confirm the listener, interface, and protocol.
- Identify network and host firewall boundaries.
- Allow only required inbound sources and ports.
- Check egress, DNS, routes, and return traffic.
- Verify load balancer health-check access.
- Review IPv4, IPv6, containers, and admin paths.
Interview questions
Further reading
- Load Balancing — route traffic across backends and manage health checks.
- Cloud Security — apply network controls and identity boundaries in cloud environments.
- HTTP and HTTPS Protocol — understand the application traffic commonly exposed through firewall rules.
- Incident Response — coordinate investigation and recovery when reachability failures affect users.
- IANA Service Name and Transport Protocol Port Number Registry lists registered service names and port numbers by transport protocol.
- Ubuntu Server firewall documentation explains UFW rules and host firewall configuration.
Conclusion
Start with the listener and its bind address, then trace the route and each firewall boundary in both directions. Keep public entry points limited, and let the application handle authentication and authorization.
Category
Related Posts
Forward and Reverse Proxies: Routing, Trust, and Use Cases
Learn how forward and reverse proxies handle HTTP traffic, CONNECT tunnels, TLS termination, caching, routing, trusted headers, and production failures.
TCP Congestion Control: Flow, Loss, and Fairness
Learn how TCP congestion control limits traffic, responds to ACKs and loss, and affects throughput, latency, and fairness, with Linux inspection commands.
Backend Configuration, Environments, and Dependencies
Learn how backend services load configuration, separate development from production, validate settings, and manage dependencies without leaking secrets.