# Troubleshooting the network: from "it is down" to the cause

A step-by-step method for network problems: ping and ICMP, traceroute, ss to see what listens, connection refused versus timeout, tcpdump to see real packets, and firewalls with nftables and ufw.

Course: [Linux & Bash for DevOps](https://devops.rajeev.pro/courses/linux), lesson 15. About 40 minutes, intermediate. Source: https://devops.rajeev.pro/courses/linux/15-troubleshooting

## What you will learn

- Follow a fixed order of checks instead of guessing
- Use ping and know what a failed ping does and doesn't prove
- Find where a path breaks with traceroute or mtr
- See what is listening, on which address, with ss
- Tell "connection refused" from a timeout, and what each one means
- Capture packets with tcpdump to prove what's on the wire
- Read and change firewall rules with nftables and ufw without locking yourself out

## A method, not guesses

**A typical incident.** It's 11 p.m. The app logs say "could not connect to database". The app
team says the database is down. The database team says it's up and they can connect fine. Someone
restarts the app, which changes nothing. Someone else restarts the database, which takes the other
apps down too. An hour later, someone finds a firewall rule that was changed that afternoon.

All of that guessing could have been five minutes of checking. "The app can't reach the database"
has a dozen possible causes. Checking them in a fixed order,
from the bottom up, finds the cause quickly and proves it, which matters when you tell another team
the problem is on their side.

> **Figure.** A troubleshooting ladder in five rungs, checked from the bottom. 1, is my side up: ip -br addr and ip route. 2, does the name resolve: getent hosts. 3, can I reach the host: ping and mtr, keeping in mind ICMP may be blocked. 4, does the port answer: nc -zv. Refused means nothing listens, timeout means a firewall drops it. 5, is the service healthy: ss -tlnp, systemctl status and the logs on the far side. tcpdump proves what's on the wire at any rung.
>
> Bottom to top. The first rung that fails is where the problem is.

The first three rungs are in the _Networking_ lesson. This lesson is about the rest: what's
reachable, what's listening, and what's in the way.

## ping: is the host there?

`ping` tests whether a host answers ICMP echo requests and reports round-trip time and packet loss. It is a
quick reachability signal, but it does not test the application's TCP port or HTTP health.

```sh
$ ping -c 3 1.1.1.1
64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=41.8 ms
64 bytes from 1.1.1.1: icmp_seq=2 ttl=57 time=33.6 ms
64 bytes from 1.1.1.1: icmp_seq=3 ttl=57 time=33.6 ms
--- 1.1.1.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2003ms
rtt min/avg/max/mdev = 33.625/36.358/41.818/3.860 ms
```

`ping` sends **ICMP** echo requests. Replies prove the host is reachable; the times show latency
and any **packet loss** points to a bad link. A failed ping proves much less: AWS security groups
and many firewalls block ICMP by default, so a perfectly healthy server may not answer. Always go on
to test the real port.

Use a short count such as `-c 3` during an investigation so the command stops on its own. Compare loss and
latency across several destinations, then test the actual service port. A common mistake is declaring a
server down because ping is blocked, or declaring an application healthy because ping succeeds.

> **Video.** [Linux Crash Course - The ping Command](https://www.youtube.com/watch?v=DOVsoWJAxuM) (Learn Linux TV)

## traceroute and mtr: where does it stop?

When the destination does not respond, a route trace shows which network hops reply along the path. `traceroute`
sends probes with increasing hop limits; `mtr` repeats the test and summarizes loss and latency over time.

```sh
$ traceroute -n 1.1.1.1           # each router (hop) on the way, and its delay
$ mtr -rwc 10 1.1.1.1             # traceroute and ping combined: loss per hop
```

Each line is one router. Where the hops stop answering is roughly where the path breaks, inside your
network, your provider's, or theirs. `* * *` on one hop in the middle is usually a router that
ignores these probes, not a failure: only loss that continues to the last hop is real. Install them
with `sudo apt install traceroute mtr-tiny`; `tracepath` needs no root.

Use traces to collect evidence about where replies stop, not as proof that the non-responding router is broken.
Routers often forward traffic while ignoring diagnostic probes. If later hops and the destination respond,
the path is working despite asterisks in the middle. A common mistake is reporting the first silent hop as the
root cause without checking the final destination.

## ss: what is listening?

`ss` shows sockets: what listens and what's connected. It replaced the older `netstat`. Use it to check whether
the expected process has opened a local port before blaming a firewall or remote network.

```sh
$ sudo ss -tlnp                   # t TCP, l listening, n numbers, p process
State  Recv-Q Send-Q  Local Address:Port  Peer Address:Port Process
LISTEN 0      4096    127.0.0.53%lo:53         0.0.0.0:*     users:(("systemd-resolve",…))
LISTEN 0      5             0.0.0.0:8099       0.0.0.0:*     users:(("python3",pid=100308,fd=3))
$ ss -tn state established        # current connections
$ ss -s                           # totals: how many connections of each state
$ sudo ss -tlnp 'sport = :443'    # just one port
```

Read the **Local Address** column: `0.0.0.0` or `*` accepts connections on every address,
`127.0.0.1` only from this machine. The single most common "works on the server, not from outside"
bug is an app bound to `127.0.0.1`.

Use `-l` for listeners, `-t` for TCP, `-n` to avoid name lookups and `-p` to show the process when permitted.
Check the bind address as well as the port: a listener on loopback is reachable only from that host. A common
mistake is looking at a UDP socket while troubleshooting TCP, or assuming `ss` shows cloud security-group
rules; it only reports local kernel sockets.

> **Video.** [How to Use the ss Command (Linux Crash Course Series)](https://www.youtube.com/watch?v=phY8Q7Woxsw) (Learn Linux TV)

## Refused or timeout?

The connection error often tells you whether the packet reached a host. A refusal usually means the host sent
back a reset because nothing accepted the port. A timeout means the client received no answer before its
deadline, which can happen when packets are dropped or the path is broken.

```sh
$ nc -zv -w 2 127.0.0.1 8099
Connection to 127.0.0.1 8099 port [tcp/*] succeeded!
$ nc -zv -w 2 127.0.0.1 8098
nc: connect to 127.0.0.1 port 8098 (tcp) failed: Connection refused
$ nc -zv -w 3 10.0.2.20 5432
nc: connect to 10.0.2.20 port 5432 (tcp) timed out: Operation now in progress
```

**Why the two failures look different.** When you connect to a port, your machine sends a "can I
connect?" packet (a TCP **SYN**). If it reaches the server and nothing is listening on that port, the
server's kernel immediately replies "no" (a TCP **reset**), and you see **Connection refused** in a
fraction of a second. If a firewall or security group sits in between and is set to _drop_ traffic,
nobody replies at all. Your machine waits, retries, and gives up: **timed out**. So a refusal proves
you reached the host, and a timeout tells you something in the path is swallowing your packets.

> **Figure.** Two cases of the app server connecting to the database on port 5432. Connection refused: the SYN reaches the db server, nothing listens on 5432, and a reset comes straight back, so the network works and the service is the problem. Timed out: a firewall or security group drops the SYN, the db server never sees it, nothing comes back and the client gives up after seconds, so check firewalls, security groups and routes.
>
> Refused: you reached the host, look at the service. Timed out: something in the path dropped it, look at firewalls.

| Result                 | Means                                            | Look at                                 |
| ---------------------- | ------------------------------------------------ | --------------------------------------- |
| succeeded              | the port is open and something answered          | the app itself: logs, `curl -v`         |
| **refused**, instantly | you reached the host; nothing listens there      | `ss -tlnp` and the service on that host |
| **timed out**          | no answer at all: packets are dropped on the way | firewalls, security groups, routes      |
| No route to host       | no path, or a firewall rejecting                 | `ip route`, the firewall's reject rules |

This one distinction halves most investigations. A timeout is almost never the application; a
refusal almost never the network.

Treat those as clues rather than absolute rules: a firewall can actively reject a connection, and a service
can fail while handling it. Compare tests from the client and server, inspect `ss`, and check each firewall
and route. A common mistake is repeatedly restarting the application after a timeout without first proving
that the request reached its host.

## tcpdump: see the real packets

When two teams each say "it's not us", `tcpdump` captures packets seen by a network interface. It can show
whether a SYN left the client, whether a reply returned, or whether the connection reached the server at all.
Capture only the host, port and duration you need because packet files can contain sensitive data.

```sh
$ sudo tcpdump -ni any port 5432                  # all traffic on port 5432
$ sudo tcpdump -ni eth0 host 10.0.2.20 and port 5432 -c 20
$ sudo tcpdump -ni any -w capture.pcap port 443   # save to a file to open in Wireshark
```

```text
10:41:02.113 IP 10.0.1.15.51544 > 10.0.2.20.5432: Flags [S], seq 381…
10:41:03.140 IP 10.0.1.15.51544 > 10.0.2.20.5432: Flags [S], seq 381…
10:41:05.188 IP 10.0.1.15.51544 > 10.0.2.20.5432: Flags [S], seq 381…
```

`[S]` is a **SYN**, the start of a TCP connection. Here it leaves three times and nothing comes back:
proof that the packets leave this server and are dropped further on. A healthy connection shows
`[S]`, then `[S.]` (SYN-ACK) from the other side, then `[.]`. A refused one shows `[R.]` (reset).

Use `-n` to avoid DNS lookups during capture, choose the right interface, and set a packet count or narrow
filter for a short investigation. Store captures with restricted permissions and delete them when no longer
needed. A common mistake is interpreting no packets on one interface as proof that no packets exist; verify
the route and capture on the correct host and interface.

## Firewalls: nftables and ufw

A firewall is a list of rules the kernel checks for every packet: is this one allowed in? The usual
safe setup is **default drop**: block everything, then allow only what the server is for (SSH, the
web ports, the database from the app subnet). Anything you forgot to allow shows up as a _timeout_,
which is why this is the last rung of the method.

Firewalls decide which packets may enter, leave or pass through a host. Linux uses the kernel's **netfilter**
framework; nftables is its current rule interface. Ubuntu offers ufw as a simpler frontend, while many
RHEL-family systems use firewalld. Cloud security groups filter traffic before it reaches the host, so the
required port must be allowed at both layers.

```sh
$ sudo ufw status verbose                 # Ubuntu: rules and default policy
$ sudo ufw allow OpenSSH                  # ALWAYS first, on a remote server
$ sudo ufw allow 443/tcp
$ sudo ufw allow from 10.0.1.0/24 to any port 5432 proto tcp   # database: app subnet only
$ sudo ufw enable
$ sudo nft list ruleset                   # what the kernel actually enforces
```

A minimal nftables policy, `/etc/nftables.conf`, that drops everything not allowed:

```text
table inet filter {
  chain input {
    type filter hook input priority 0; policy drop;
    ct state established,related accept      # replies to our own connections
    iif lo accept                            # this machine talking to itself
    tcp dport 22 accept                      # SSH
    tcp dport { 80, 443 } accept             # web
    icmp type echo-request accept            # allow ping
  }
}
```

```sh
$ sudo nft -c -f /etc/nftables.conf       # check the file without applying it
$ sudo systemctl enable --now nftables    # load it now and at boot
```

> **Don't lock yourself out.** Add the SSH rule before turning on a default-drop policy, keep a second session open, and know how to reach the console (the *Booting* lesson). Use either ufw or a hand-written nftables file on a server, not both: they'll fight over the same rules.

Keep rules narrow: a protocol, a port and a source. Two mistakes cause most firewall incidents:

- **Too wide.** Opening the database port to everyone because one app needs it. Allow only the app's
  subnet or host, as in the `ufw` example above.
- **Only one layer opened.** In the cloud, traffic passes the security group _and then_ the host
  firewall. Opening the port in the security group but not in `ufw` (or the other way round) gives
  you a timeout, and each team swears their layer is open. Check both.

> **In production.** Write down what you saw at each rung as you go: the exact error, the time, which host. "Port 5432 times out from 10.0.1.15 at 10:41, SYNs leave with no reply (tcpdump attached)" gets fixed in minutes. "The database is down" starts an argument.

## Mission: Prove where a connection fails

Write port-check.sh: given a host and a port, test DNS, then the TCP port, and say in plain words what failed and where to look next. Test it on a port that's open, one that refuses, and a name that doesn't exist.

- You need: Any Linux machine
- You'll have: A one-line verdict for each check

```sh
$ cat > ~/port-check.sh <<'EOF'
#!/usr/bin/env bash
host=${1:?usage: port-check.sh <host> <port>}; port=${2:?usage: port-check.sh <host> <port>}
ip=$(getent ahostsv4 "$host" | awk 'NR==1 {print $1}')
[[ -n $ip ]] || { echo "FAIL dns: $host does not resolve. Check /etc/hosts and resolvectl."; exit 1; }
out=$(nc -zv -w 3 "$ip" "$port" 2>&1)
case "$out" in
  *succeeded*) echo "OK   $host ($ip) port $port is open. If the app still fails, read its logs." ;;
  *refused*)   echo "FAIL refused: $ip answered, nothing listens on $port. Run ss -tlnp there."; exit 1 ;;
  *)           echo "FAIL timeout: no answer from $ip:$port. Check firewalls and security groups."; exit 1 ;;
esac
EOF
$ python3 -m http.server 8099 > /dev/null 2>&1 & sleep 1   # a test server on 8099
$ bash ~/port-check.sh localhost 8099
OK   localhost (127.0.0.1) port 8099 is open. If the app still fails, read its logs.
$ bash ~/port-check.sh localhost 8098
FAIL refused: 127.0.0.1 answered, nothing listens on 8098. Run ss -tlnp there.
$ bash ~/port-check.sh no-such-host.invalid 80
FAIL dns: no-such-host.invalid does not resolve. Check /etc/hosts and resolvectl.
$ kill %1
```

The exit code is 1 on every failure, so this works in a deploy pipeline or a cron health check. To
see a timeout, point it at an address that drops packets, such as `10.255.255.1 80` on most networks.

## Try it

- Run `ping -c 3 1.1.1.1` and read the loss and round-trip times.
- Run `ss -tlnp` (with sudo to see every process) and name what listens on each port.
- Start `python3 -m http.server 8099`, then test it with `nc -zv 127.0.0.1 8099`, and try port 8098 to see "refused".
- Install mtr (`sudo apt install mtr-tiny`) and run `mtr -rwc 5 1.1.1.1`.
- On a VM, capture five DNS packets with `sudo tcpdump -ni any -c 5 port 53` while you run `getent hosts example.com`.
- Read your firewall rules with `sudo nft list ruleset` or `sudo ufw status verbose`.

## Quiz

1. curl to port 5432 says "Connection refused" straight away. What does that tell you?
   - A firewall is dropping the packets
   - **The packet reached the host, but nothing is listening on that port (or it listens on another address)** (answer)
   - DNS is broken
   Why: Refused is an answer: the host sent back a reset. Check ss -tlnp there. A firewall that drops packets produces a timeout instead.

2. ping to a cloud server fails, but its website loads. Why?
   - The server is down
   - **ICMP is blocked by a firewall or security group; the server itself is fine** (answer)
   - ping only works on local networks
   Why: Many networks block ICMP. A failed ping proves little; test the port your service actually uses, with nc -zv or curl.

3. ss -tlnp shows your app on 127.0.0.1:8080. Other servers can't reach it. Why?
   - **127.0.0.1 means it only accepts connections from this machine** (answer)
   - Port 8080 is blocked by Linux
   - ss is out of date
   Why: An app bound to 127.0.0.1 is local only. Make it listen on 0.0.0.0 (all addresses) or the server's private IP, then open the firewall for it.

4. Before enabling a firewall on a remote server over SSH, what must you do first?
   - Nothing
   - **Allow SSH (port 22) in the rules, and keep a console or second session ready** (answer)
   - Reboot
   Why: A default-deny firewall without an SSH rule cuts your own connection. sudo ufw allow OpenSSH before sudo ufw enable.

5. What does tcpdump -ni any port 443 show?
   - **Every packet on any interface to or from port 443, with addresses as numbers** (answer)
   - Only blocked packets
   - The firewall rules for 443
   Why: -n skips name lookups, -i any listens on all interfaces. Seeing packets leave with no reply, for example, proves the problem is beyond this host.

## Resources

- [ss(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/ss.8.html) (Ubuntu manpages)
- [tcpdump(8) manual](https://manpages.ubuntu.com/manpages/noble/man8/tcpdump.8.html) (Ubuntu manpages)
- [nftables wiki: quick reference](https://wiki.nftables.org/wiki-nftables/index.php/Quick_reference-nftables_in_10_minutes) (nftables)
- [Ubuntu Server: firewall (ufw)](https://documentation.ubuntu.com/server/how-to/security/firewalls/) (Ubuntu)
- [LPIC-1 objective 109.3: basic network troubleshooting](https://wiki.lpi.org/wiki/LPIC-1_Objectives_V5.0) (Linux Professional Institute)
