# Linux Networking Basics: Routing, DNS and Network Namespaces

> A walk through Linux networking with ip, resolv.conf and ip netns: routing tables and gateways, how name resolution works, and finally building an isolated virtual network by hand with veth, a bridge and iptables

- URL: https://lcxlab.com/en/post/linux-networking-basics
- Author: Miles Hsu
- Published: 2026-11-03
- Updated: 2026-11-05
- Category: Linux
- Tags: Linux, Networking
- License: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/deed.en)

---

Most people use Windows or macOS, and most Linux distributions have a desktop edition too, so networking is taken for granted. But once you deal with containers, virtual machines or text-only server editions of Linux, you run into things that are hard to explain: why can I ping an IP but not connect to it? Why does `ping` find a host while `nslookup` says it doesn't exist? Why does a container have its own `eth0`?

Using only commands built into Linux, this post covers the basics behind these questions in three parts:

1. **Routing and gateways**: how a packet gets from one machine to another network
2. **DNS**: how a name is resolved to an IP
3. **Network namespaces**: building two isolated network environments by hand with `ip netns`, veth and a bridge, then using iptables to let them reach out and be reached

---

## Lab environment

The first two parts only observe things and work on any Linux machine. The third part changes routes and iptables, so **use a separate, clean VM**. Don't do it on a machine already running Docker, Kubernetes or firewall rules: the rules get mixed together, making them hard to observe, and you may break existing services.

This post uses an Ubuntu 24.04 VM (called `netlab` below) on libvirt's `default` NAT network, `192.168.122.0/24`.

### Spinning up a VM quickly with libvirt

This is the short version: an Ubuntu Cloud Image plus cloud-init gets a VM up in a dozen seconds or so. For installing the tools and what the options mean, see:

[Preparing Practice VMs with KVM and cloud-init](https://lcxlab.com/en/post/cka-kubeadm-lab-setup)

```bash
IMG_DIR="/var/lib/libvirt/images"

# 1. Download the Cloud Image as a base image (skip if you already have it)
[ -f "$IMG_DIR/noble-base.img" ] || sudo curl -L -o "$IMG_DIR/noble-base.img" \
  https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img

# 2. Create netlab's disk on top of the base image
sudo qemu-img create -f qcow2 -F qcow2 -b "$IMG_DIR/noble-base.img" "$IMG_DIR/netlab.qcow2" 10G

# 3. cloud-init: hostname, password and SSH key
cat > netlab-user-data.yaml <<YAML
#cloud-config
hostname: netlab
password: ubuntu
chpasswd: { expire: false }
ssh_authorized_keys:
  - $(cat ~/.ssh/id_ed25519.pub)
YAML

# 4. Create and boot
sudo virt-install \
  --name netlab --memory 2048 --vcpus 2 \
  --disk "$IMG_DIR/netlab.qcow2" \
  --os-variant ubuntu24.04 --import \
  --cloud-init user-data=netlab-user-data.yaml \
  --network network=default \
  --graphics none --noautoconsole
```

Find the IP and SSH in (the default user is `ubuntu`):

```bash
sudo virsh domifaddr netlab
ssh ubuntu@<netlab IP>
```
>Check: after logging in, `hostname` prints netlab.

Unless noted otherwise, the commands below run inside `netlab`.

---

## Networking on Linux

### Interfaces and IPs

First, see which network interfaces the machine has and their IPs:

```bash
ip link              # list interfaces (L2): state UP/DOWN and MAC
ip addr              # list interfaces and IPs (L3)
ip -br addr          # brief version, one line per interface; the one you'll use most
```

A freshly created VM usually has just two interfaces: `lo` (`127.0.0.1`) and one physical NIC (such as `enp1s0`). If Docker, libvirt or a VPN is installed, you'll also see virtual interfaces like `docker0`, `virbr0` and `wg0`; most of them are exactly what the third part builds by hand.

![164001](https://lcxlab.com/images/posts/linux-networking-basics/164001.webp)

### Switches and routers: same network vs. different networks

- **Same network** (e.g. `192.168.122.195` and `192.168.122.196`): packets go straight to the other machine over L2 (a switch / bridge), with no router involved.
- **Different networks**: packets are handed to a **router**, which forwards them to the other network. How does the machine know whom to hand them to? It looks at the **routing table**.

```bash
ip route
#default via 192.168.122.1 dev enp1s0 proto dhcp src 192.168.122.195 metric 100
#192.168.122.0/24 dev enp1s0 proto kernel scope link src 192.168.122.195 metric 100
#192.168.122.1 dev enp1s0 proto dhcp scope link src 192.168.122.195 metric 100
```

These three lines mean:

| Route | Meaning |
|--|--|
| `default via 192.168.122.1` | Every other destination goes to `192.168.122.1` (the default gateway, here libvirt's `virbr0`) |
| `192.168.122.0/24 dev enp1s0` | Destinations on the same network are sent directly out of `enp1s0`, not through the gateway |
| `192.168.122.1 dev enp1s0` | A host route just for the gateway itself, telling the kernel the gateway is directly reachable on `enp1s0` |

The fields after each route:

| Field | Meaning |
|--|--|
| `dev enp1s0` | Which NIC to send out of |
| `proto dhcp` / `proto kernel` | Who added the route: `dhcp` is the DHCP client (systemd-networkd on Ubuntu), based on its lease; `kernel` is the network route the kernel creates automatically when an IP is configured |
| `scope link` | The destination is on this link and directly reachable, with no other router in between |
| `src 192.168.122.195` | The default source IP for packets sent via this route |
| `metric 100` | Priority: when several routes match, the lower number wins |

>[!NOTE] Why an extra route for the gateway?
>With the `192.168.122.0/24` line the gateway is already directly reachable, so the third line looks redundant. systemd-networkd adds it when it gets a gateway from DHCP, to guarantee the gateway is always directly reachable: even if DHCP hands out a gateway outside the machine's own network (some cloud environments do), the default route won't break because its next hop is unreachable.

Adding / removing routes by hand:

```bash
sudo ip route add 10.10.0.0/24 via 192.168.122.20   # send 10.10.0.0/24 via 192.168.122.20
sudo ip route del 10.10.0.0/24
ip route get 10.10.0.5                               # ask the kernel: which route will this IP take?
```

`ip route get` is handy for troubleshooting: once the routing table gets long it's easy to misread by eye, and asking the kernel directly is the most accurate.

The neighbor (ARP) table records which MAC each IP on the same network belongs to:

```bash
ip neigh
#192.168.122.1 dev enp1s0 lladdr 52:54:00:b1:64:5a DELAY
```

`lladdr` is the MAC of the gateway `virbr0` (the `52:54:00` prefix belongs to QEMU/KVM virtual NICs), and the last column is the entry's state:

| State | Meaning |
|--|--|
| `REACHABLE` | Recently confirmed the neighbor is there; can be used directly |
| `STALE` | Not confirmed for a while; still usable, and will be confirmed the next time a packet is sent |
| `DELAY` | A packet has been sent using this entry; waiting a moment for a reply that proves the neighbor is there, and sending an ARP request if none arrives |
| `PROBE` | Sending ARP requests to confirm the neighbor |
| `FAILED` | The neighbor didn't answer; this IP probably doesn't exist on the network or is powered off |
| `INCOMPLETE` | First request sent, no reply yet |

We see `DELAY` here because the SSH connection just used the gateway's entry, which had been `STALE`. Run the command again a few seconds later and it's usually back to `REACHABLE`. When troubleshooting an unreachable host on the same network, `FAILED` or `INCOMPLETE` means the problem is at L2: the other machine is off, the IP is wrong, or it isn't on the same network.

>[!NOTE] Settings made with `ip` vanish on reboot
>Settings made with `ip addr add` and `ip route add` live only in memory. To make them permanent, write them into `/etc/netplan/*.yaml` on Ubuntu, or use NetworkManager (`nmcli`) on Fedora / RHEL.

### Making Linux a router: ip_forward

When Linux receives a packet whose destination isn't itself, it drops it by default. To have it forward packets like a router, turn on IP forwarding:

```bash
cat /proc/sys/net/ipv4/ip_forward     # 0 = don't forward, 1 = forward
sudo sysctl -w net.ipv4.ip_forward=1  # takes effect now, lost on reboot

# permanent
echo "net.ipv4.ip_forward = 1" | sudo tee /etc/sysctl.d/99-ip-forward.conf
sudo sysctl --system
```

Any machine that forwards packets between two networks needs this, such as a VPN gateway or a host running VMs or containers. The experiment in the third part needs it too.

---

## DNS on Linux

### /etc/hosts: the simplest name resolution

Without a DNS server, you can write names straight into `/etc/hosts`:

```bash
cat <<EOF | sudo tee -a /etc/hosts
192.168.122.11 db
192.168.122.12 web
EOF
ping -c 1 db
```

With many machines, editing `/etc/hosts` on each one becomes unmanageable, so the table is centralized on a **DNS server** that everyone asks.

### /etc/resolv.conf: which DNS server to ask

```bash
cat /etc/resolv.conf
# nameserver 127.0.0.53
# options edns0 trust-ad
# search .
```

| Field | Purpose |
|--|--|
| `nameserver` | The DNS server to ask; there can be several lines |
| `search` | Suffixes appended automatically when a name isn't fully qualified. With `search example.com`, looking up `web` tries `web.example.com` |
| `options ndots:N` | If a name has fewer than N dots, apply `search` first; the default is 1 |

For example, once a company network sets `search corp.example.com`, `ssh build01` automatically becomes `ssh build01.corp.example.com`.

### /etc/nsswitch.conf: hosts first or DNS first?

When both `/etc/hosts` and DNS are configured, `/etc/nsswitch.conf` decides which comes first:

```bash
grep ^hosts /etc/nsswitch.conf
# hosts: files dns
```

`files dns` means check `/etc/hosts` first, and ask DNS if the name isn't there.

### systemd-resolved and 127.0.0.53

Distributions like Ubuntu and Fedora run `systemd-resolved` by default. The `127.0.0.53` in `/etc/resolv.conf` is a local stub resolver it runs for caching and forwarding; to see the real upstream DNS, use `resolvectl`:

```bash
ls -l /etc/resolv.conf                 # actually a link to /run/systemd/resolve/stub-resolv.conf
resolvectl status                      # the real upstream DNS (usually 192.168.122.1 under libvirt)
cat /run/systemd/resolve/resolv.conf   # the version listing the real upstream DNS
```

This design is convenient on the host itself, but it has a common pitfall: `127.0.0.53` only means something in this host's own network environment. Hand this `resolv.conf` unchanged to an isolated network environment (a container, a network namespace) and `127.0.0.53` points at itself, where no DNS service is running, so names can't be resolved. In that case give it `/run/systemd/resolve/resolv.conf`, the one listing the real upstream. The third part runs into exactly this problem.

### Lookup tools: nslookup, dig and getent

```bash
nslookup example.com          # simple lookup
dig example.com +short        # show only the result
dig @1.1.1.1 example.com      # choose which DNS server to ask
getent hosts db               # resolves in nsswitch.conf order, so it reads /etc/hosts
```

>[!WARNING] ❗nslookup / dig ignore /etc/hosts
>`nslookup` and `dig` ask the DNS server directly and don't read `/etc/hosts`. A name in `/etc/hosts` works with `ping` and `curl`, but `nslookup` says it can't be found; that's expected. To see what applications actually resolve, use `getent hosts`.

Common record types:

| Type | Contents | Example |
|--|--|--|
| A | Name → IPv4 | `example.com → 93.184.215.14` |
| AAAA | Name → IPv6 | |
| CNAME | Name → another name | `www.example.com → example.com` |
| MX | Mail server | |
| SRV | Port and host of a service | `_sip._tcp.example.com` |
| PTR | IP → name (reverse lookup) | `dig -x 1.1.1.1` |

---

## Network Namespace on Linux

Linux **network namespaces** split networking into several independent environments. Each has its own interfaces, IPs, routing table, ARP table and iptables rules, and none can see the others. A container has its own `eth0` and IP precisely because it runs in its own network namespace.

Next, we build the following environment by hand on `netlab`:

<!-- ```text
          ┌─────────── netlab (VM) ────────────┐
          │                                    │
 [red]    │  veth-red ─┐                       │
192.168.15.1           │                       │
          │        v-net-0 (bridge)  enp1s0 ───┼── 192.168.122.0/24 ── outside network
 [blue]   │  veth-blue ┘  192.168.15.5         │
192.168.15.2                                   │
          └────────────────────────────────────┘
``` -->

![networking|bg-dark](/images/posts/linux-networking-basics/networking.webp)

### 1. Create the namespaces

```bash
sudo ip netns add red
sudo ip netns add blue
ip netns list
```

There are two ways to run a command inside a namespace:

```bash
sudo ip netns exec red ip link   # general form, runs any command
sudo ip -n red link              # shorthand for ip commands
```

A new namespace has nothing but a `lo` that is `DOWN`. It can't see the host's `enp1s0`, and its routing and ARP tables are empty. That's isolation.

### 2. Connect them directly with a veth pair

veth (virtual ethernet) devices always come in pairs, like the two ends of a network cable: a packet sent into one end comes out of the other.

```bash
sudo ip link add veth-red type veth peer name veth-blue    # create a pair
sudo ip link set veth-red netns red                        # put one end in red
sudo ip link set veth-blue netns blue                      # and the other in blue

sudo ip -n red addr add 192.168.15.1/24 dev veth-red
sudo ip -n blue addr add 192.168.15.2/24 dev veth-blue
sudo ip -n red link set veth-red up
sudo ip -n blue link set veth-blue up

sudo ip netns exec red ping -c 2 192.168.15.2
```
>Check: the ping gets replies, and `ip link` on the host no longer shows veth-red / veth-blue (they're inside the namespaces now).

Wiring two namespaces together with one cable works, but with more environments you can't run a cable between every pair, so we switch to a **bridge** (a virtual switch). Delete this cable first; deleting one end removes the other too:

```bash
sudo ip -n red link del veth-red
```

### 3. Connect several namespaces with a bridge

```bash
# Create a bridge on the host; it is itself a network interface on the host
sudo ip link add v-net-0 type bridge
sudo ip link set v-net-0 up

for ns in red blue; do
  sudo ip link add veth-$ns type veth peer name veth-$ns-br   # one end for the namespace, one for the bridge
  sudo ip link set veth-$ns netns $ns
  sudo ip link set veth-$ns-br master v-net-0
  sudo ip link set veth-$ns-br up
  sudo ip -n $ns link set veth-$ns up
done

sudo ip -n red addr add 192.168.15.1/24 dev veth-red
sudo ip -n blue addr add 192.168.15.2/24 dev veth-blue

sudo ip netns exec red ping -c 2 192.168.15.2
```
>Check: `bridge link` lists both veth-red-br and veth-blue-br attached to v-net-0.

The host itself still can't reach `192.168.15.0/24`, because none of its interfaces is on that network. Give the bridge an IP and the host becomes a member of the network:

```bash
sudo ip addr add 192.168.15.5/24 dev v-net-0
ping -c 2 192.168.15.1
```

Docker's default `docker0` and libvirt's `virbr0` are both bridges like this.

### 4. Reaching the outside: default gateway and NAT

Pinging something outside from red (say the VM's gateway, `192.168.122.1`) fails, because red's routing table only knows `192.168.15.0/24`. First make the bridge the default gateway for red and blue:

```bash
sudo ip -n red route add default via 192.168.15.5
sudo ip -n blue route add default via 192.168.15.5
sudo sysctl -w net.ipv4.ip_forward=1     # let the host forward packets
```

Packets can now get out, but replies can't get back: machines outside don't know the private IP `192.168.15.1` and have no idea where to send replies. The fix is to replace the source IP with the host's own IP as packets leave the host, which is **SNAT / MASQUERADE**:

```bash
sudo iptables -t nat -A POSTROUTING -s 192.168.15.0/24 ! -o v-net-0 -j MASQUERADE

sudo ip netns exec red ping -c 2 192.168.122.1
sudo ip netns exec red ping -c 2 8.8.8.8
```
>Check: both pings get replies. `sudo iptables -t nat -L POSTROUTING -n -v` shows the packet counter of the MASQUERADE rule going up.

A home router that lets several phones and computers share one public IP does the same thing.

Trying `ping example.com` here may fail, for exactly the systemd-resolved reason from the previous part: `ip netns exec` reuses the host's `/etc/resolv.conf`, which says `127.0.0.53`, but inside red `127.0.0.53` is red's own `lo`, with no DNS service on it. `ip netns` supports a dedicated config per namespace:

```bash
sudo mkdir -p /etc/netns/red
echo "nameserver 192.168.122.1" | sudo tee /etc/netns/red/resolv.conf
sudo ip netns exec red ping -c 2 example.com
```

### 5. Letting outside traffic in: DNAT (port forwarding)

The other way round, to let the outside reach a service inside blue, rewrite the destination from "host IP:port" to "blue's IP:port" as packets enter the host, which is **DNAT**:

```bash
# Run a simple HTTP server in blue
sudo ip netns exec blue python3 -m http.server 80 &

# Packets sent to port 8080 on the host go to port 80 in blue
sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.15.2:80
```

Then test **from another machine** (for example the physical host running the VM, not netlab itself):

```bash
curl http://<netlab IP>:8080
```
>Check: you see the directory listing from python's http.server.

![165938](https://lcxlab.com/images/posts/linux-networking-basics/165938.webp)

>[!WARNING] ❗curl on netlab itself fails
>`PREROUTING` only handles packets coming in from outside; packets netlab generates itself go through the `OUTPUT` chain and don't hit this rule. To connect through 8080 locally as well, add the same DNAT rule to the `OUTPUT` chain.

Behind `docker run -p 8080:80` is a similar DNAT rule.

### 6. Cleanup

```bash
sudo kill %1                                   # stop http.server
sudo ip netns del red
sudo ip netns del blue                         # deleting a namespace deletes the veth inside it
sudo ip link del v-net-0
sudo iptables -t nat -F                        # only OK on a practice machine like netlab; on real machines delete only the rules you added
sudo rm -rf /etc/netns/red
```

---

## Inspecting existing network namespaces

`ip netns list` only lists namespaces under `/var/run/netns/`. Namespaces created by programs themselves (such as containers) aren't necessarily there, but `lsns` finds them all, and `nsenter` gets you inside:

```bash
lsns -t net                          # list every network namespace on the system and its PID
sudo nsenter -t <PID> -n ip addr     # run ip addr in that PID's network namespace
sudo nsenter -t <PID> -n ip route
```

Let's try it with a container. The Ubuntu Cloud Image has no Docker by default, so install it from the Ubuntu repositories:

```bash
sudo apt-get update
sudo apt-get install -y docker.io
sudo docker version      # both Client and Server should show a version
```

Then run an nginx container and enter its network namespace through its PID:

```bash
sudo docker run -d --name web nginx
PID=$(sudo docker inspect -f '{{.State.Pid}}' web)
echo $PID                             # make sure you got a number; empty means the container isn't running
sudo nsenter -t $PID -n ip addr       # eth0 and IP inside the container (172.17.0.0/16 by default)
ip link | grep veth                   # the matching veth end on the host
```
>Check: nsenter shows eth0 as 172.17.0.x, and the host has a new vethXXXX with master docker0.

The actual output (the long line after `docker run` is the container ID; `2561` is the container's PID):

![170706](https://lcxlab.com/images/posts/linux-networking-basics/170706.webp)

The first half is what the container sees: just `lo` and `eth0`, with IP `172.17.0.2`. The second half is the host's veths: besides the two built by hand in the third part, there is a new `veth45e4011` attached to `docker0`. That's the host end of the veth pair Docker created for the container, the same structure as our hand-made `veth-red-br` attached to `v-net-0`.

>[!WARNING] ❗When PID is empty
>If the `docker` command fails, `$PID` is an empty string and the command becomes `nsenter -t -n ip addr`. `-n` is parsed as the PID, giving `nsenter: failed to parse pid: '-n'`. Check that `echo $PID` prints a number first.

### The @ifN after a veth name

veths on the host show up as `veth-red-br@if7`:

```bash
ubuntu@netlab:~$ ip link | grep veth
6: veth-red-br@if7: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master v-net-0 state UP ...
8: veth-blue-br@if9: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master v-net-0 state UP ...
```

- The leading `6:` is this interface's number on the host (its ifindex)
- `@if7` means the other end of the veth is interface number 7, and it's in **another namespace**, so the host can't see its name, only its number
- `master v-net-0` means the interface is attached to the bridge `v-net-0`

Inside the namespace you can match up the other end:

```bash
ubuntu@netlab:~$ sudo ip -n red link
1: lo: <LOOPBACK> mtu 65536 qdisc noop state DOWN mode DEFAULT group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
7: veth-red@if6: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default qlen 1000
    link/ether a2:5e:c6:ee:3e:8e brd ff:ff:ff:ff:ff:ff link-netnsid 0
```

`veth-red` in red is number 7, and `@if6` points back to `veth-red-br`, number 6 on the host; each side points at the other. Containers work the same way:

| Where | Interface | Points to |
|--|--|--|
| Host | `6: veth-red-br@if7` | Number 7 in red |
| red | `7: veth-red@if6` | Number 6 on the host |
| Host | `11: veth45e4011@if2` | Number 2 in the container |
| Container | `2: eth0@if11` | Number 11 on the host |

When troubleshooting container networking, use `nsenter` to see the container's `eth0@ifN`, then find number N with `ip link` on the host. That tells you which veth the container uses and which bridge it's attached to.

Two small details:

- red's `lo` is `DOWN` because when we built the namespace by hand we only brought `veth-red` up and left `lo` alone, so connecting to `127.0.0.1` inside red fails; containers created by Docker get `lo` set up too. If you need it, run `sudo ip -n red link set lo up`.
- `link-netnsid 0` identifies the namespace the other end of the veth is in, numbered 0 from this namespace's point of view; here it's the host's root namespace.

---

## Command cheat sheet

| Goal | Command |
|--|--|
| Interfaces and IPs | `ip -br addr`, `ip link` |
| Routes / which route an IP takes | `ip route`, `ip route get <IP>` |
| ARP / neighbor table | `ip neigh` |
| Listening ports | `ss -tlnp` |
| Is packet forwarding on? | `sysctl net.ipv4.ip_forward` |
| DNS settings | `cat /etc/resolv.conf`, `resolvectl status` |
| Resolve a name the way the system does | `getent hosts <name>` |
| Ask DNS directly | `dig <name>`, `nslookup <name>` |
| Manage namespaces | `ip netns add / del / exec`, `ip -n <ns> ...` |
| Enter another program's namespace | `nsenter -t <PID> -n <cmd>` |
| Interfaces on a bridge | `bridge link` |
| NAT rules | `sudo iptables -t nat -L -n -v` |

---

## Further reading

The namespaces, veths, bridge and NAT built by hand here are exactly what Kubernetes network plugins and kube-proxy set up automatically on every node. If you're interested, read on:

[Kubernetes Networking: How Do Pods Talk to Each Other?](https://lcxlab.com/en/post/cni-plugins-for-kubernetes)

[Kubernetes Networking: Service, DNS, NetworkPolicy and Gateway API](https://lcxlab.com/en/post/cka-networking)

---

References:

[1] ip(8) - https://man7.org/linux/man-pages/man8/ip.8.html

[2] ip-netns(8) - https://man7.org/linux/man-pages/man8/ip-netns.8.html

[3] veth(4) - https://man7.org/linux/man-pages/man4/veth.4.html

[4] resolv.conf(5) - https://man7.org/linux/man-pages/man5/resolv.conf.5.html

[5] nsswitch.conf(5) - https://man7.org/linux/man-pages/man5/nsswitch.conf.5.html

[6] systemd-resolved.service(8) - https://www.freedesktop.org/software/systemd/man/latest/systemd-resolved.service.html

[7] nsenter(1) - https://man7.org/linux/man-pages/man1/nsenter.1.html

Image credits:

Cover: [Tux](https://commons.wikimedia.org/wiki/File:Tux.svg) by Larry Ewing (lewing@isc.tamu.edu), created with The GIMP
