← DevOps← DevOps
DevOpsDevOps18 Th7, 2026Jul 18, 202620 phút đọc17 min read

Mạng máy tính & Các giao thứcNetworking & Protocols

Thuộc bộ kiến thức DevOps Roadmap.

Tổng quan

Mạng là nền tảng mà mọi hệ thống phân tán chạy trên đó. Dù bạn đang debug vì sao pod không kết nối được database, cấu hình TLS termination trên load balancer, hay viết rule cho security group, bạn đều đang làm việc với cùng một nhóm giao thức: IP, TCP/UDP, DNS, HTTP và TLS. Một DevOps engineer hiểu rõ các tầng này có thể suy luận chính xác về sự cố (“đây là lỗi DNS, lỗi routing, hay lỗi ứng dụng?”) thay vì đoán mò — đó là khác biệt giữa một bản vá năm phút và một sự cố kéo dài hai giờ.

Hai mô hình tư duy kinh điển là mô hình OSI 7 tầng và stack TCP/IP 4 tầng thực dụng. OSI là công cụ giảng dạy và từ vựng chung (“L4 load balancer”, “L7 firewall”); TCP/IP là thứ mạng thật triển khai. Bên trên là các giao thức ứng dụng bạn chạm vào hằng ngày: DNS để đặt tên, HTTP(S) cho gần như toàn bộ traffic giữa các service, TLS cho mã hóa và định danh, SSH để quản trị.

Hạ tầng cloud biến networking thành thứ lập trình được — VPC, subnet, route table, NAT gateway, security group — nhưng khái niệm nền tảng không đổi. Nắm vững tính toán CIDR, luồng phân giải DNS và TLS handshake sẽ hữu ích trên mọi cloud lẫn môi trường on-prem. Mục tiêu của trang này là cho bạn đủ mô hình để các công cụ ở mức gói tin (dig, curl -v, tcpdump) trở thành cuộc đối thoại với mạng thay vì một câu thần chú.

Kiến thức nền tảng

Mô hình OSI vs stack TCP/IP

Tầng OSITênTầng TCP/IPVí dụHỏng ở đây là gì
7ApplicationApplicationHTTP, DNS, SSH, SMTPRequest sai, 5xx, auth
6PresentationApplicationTLS (tương đối), serializationLỗi cert/handshake
5SessionApplicationQuản lý sessionMất session/state
4TransportTransportTCP, UDP, QUICPort đóng, RST, timeout
3NetworkInternetIP, ICMP, routingKhông có route, sai subnet
2Data LinkLinkEthernet, ARP, Wi-FiARP, MTU, VLAN
1PhysicalLinkCáp, sóng radioĐứt cáp/NIC hỏng

Thực tế, kỹ sư dùng số tầng OSI như từ vựng (“L4 vs L7 load balancing”) trong khi stack thật hoạt động theo TCP/IP. Mỗi tầng bọc tầng trên nó bằng một header (encapsulation): một HTTP request trở thành một TCP segment, nằm trong một IP packet, nằm trong một Ethernet frame.

TCP vs UDP — hai giao thức transport bạn gặp liên tục:

TCPUDP
Kết nốiHướng kết nối (bắt tay 3 bước: SYN → SYN-ACK → ACK)Không kết nối — gửi và quên
Độ tin cậyCó thứ tự, truyền lại, có ACKKhông có — app tự xử lý mất gói nếu cần
Flow/congestion controlKhông
Overhead / độ trễCao hơn (handshake, ACK)Thấp hơn
Được dùng bởiHTTP/1–2, SSH, SMTP, hầu hết APIDNS, DHCP, NTP, QUIC/HTTP/3, VoIP, streaming

Kết nối TCP kết thúc bằng bắt tay FIN; một gói RST đột ngột nghĩa là “không ai lắng nghe” hoặc “kết nối bị đóng cưỡng bức” — tín hiệu rất phổ biến khi port đóng hoặc app crash. MTU (thường 1500 byte) quan trọng: gói lớn hơn path MTU sẽ bị phân mảnh hoặc drop, và MTU lệch nhau (hay gặp với VPN/mạng overlay) gây treo bí ẩn khi payload lớn.

Địa chỉ IP, subnet và CIDR

Ký hiệu CIDR 10.0.0.0/16 nghĩa là 16 bit đầu là network prefix, còn lại 2^16 = 65.536 địa chỉ. Độ dài prefix là số bit 1 đứng đầu trong subnet mask.

CIDRMaskSố địa chỉDùng điển hình
/8255.0.0.016.777.216Dải private khổng lồ (10.0.0.0/8)
/16255.255.0.065.536Cả một VPC
/20255.255.240.04.096Subnet lớn / AZ
/24255.255.255.0256 (254 dùng được)Subnet tiêu chuẩn
/28255.255.255.24016Subnet nhỏ (bastion, endpoint)
/32255.255.255.2551Một host đơn (rule security group)

Điểm cần nhớ:

NAT (Network Address Translation) cho phép nhiều địa chỉ private dùng chung IP public. NAT gateway giúp private subnet có kết nối internet chiều ra (để update, gọi API) mà không mở chiều vào — nền tảng của mô hình “private subnet” nơi tầng app và DB hoàn toàn không có IP public.

ip addr                          # interface và địa chỉ
ip route                         # bảng routing (next-hop cho từng prefix)
ping -c 3 8.8.8.8                # kiểm tra kết nối tầng 3
traceroute example.com           # dò đường đi từng hop
mtr example.com                  # traceroute liên tục + thống kê mất gói
ss -tlnp                         # các TCP socket đang lắng nghe và tiến trình sở hữu
nc -zv host 443                  # port có mở không? (probe L4)
ipcalc 10.0.0.0/20               # công cụ tính subnet

DNS

DNS dịch tên miền thành các bản ghi — nó là danh bạ của internet, và đứng sau một tỉ lệ sự cố đáng ngạc nhiên (“luôn là DNS”).

Luồng phân giải: stub resolver (OS của bạn) → recursive resolver (ví dụ 1.1.1.1, 8.8.8.8, hoặc resolver của VPC) → root server (.) → TLD server (.com) → authoritative server của zone → trả kết quả, được cache ở mỗi chặng theo TTL.

Bản ghiMục đích
A / AAAATên → địa chỉ IPv4 / IPv6
CNAMEAlias sang tên khác (không dùng được ở zone apex)
ALIAS / ANAME”Giống CNAME” nhưng dùng được ở apex (tùy provider: Route 53 alias, v.v.)
MXMail server của domain (kèm priority)
TXTVăn bản tùy ý — SPF, DKIM, DMARC, xác minh domain
NSỦy quyền zone cho name server
SOAMetadata của zone (primary NS, serial, timer refresh/retry/expire)
SRVVị trí service (protocol, port, host)
PTRTra cứu ngược (IP → tên), dùng cho uy tín mail
CAACA nào được phép cấp certificate cho domain
dig +short example.com A
dig example.com MX @1.1.1.1      # truy vấn một resolver cụ thể
dig +trace example.com           # lần theo toàn bộ chuỗi ủy quyền từ root
dig -x 1.1.1.1                   # tra cứu ngược (PTR)
host example.com                 # tra cứu nhanh
resolvectl status                # host này thực sự đang dùng resolver nào?

TTL là một sự đánh đổi: TTL thấp (60s) nghĩa là lan truyền nhanh và failover nhanh nhưng tải truy vấn và độ trễ cao hơn; TTL cao (nhiều giờ) nghĩa là cache hiệu quả nhưng thay đổi chậm. Hạ TTL trước khi migrate theo kế hoạch, rồi nâng lại sau đó.

Trong hạ tầng, DNS còn là công cụ điều phối traffic: routing theo trọng số, độ trễ, vị trí địa lý và failover (Route 53, Cloudflare, NS1), và service discovery (Consul, CoreDNS của Kubernetes phân giải service.namespace.svc.cluster.local). Các biến thể bảo mật hiện đại DoH (DNS over HTTPS) và DoT (DNS over TLS) mã hóa truy vấn vốn trước đây là plaintext.

HTTP và HTTPS

NhómÝ nghĩaCode quan trọng
2xxThành công200 OK, 201 Created, 204 No Content, 206 Partial
3xxRedirect301 vĩnh viễn, 302/307 tạm thời, 304 Not Modified (cache)
4xxLỗi client400 bad request, 401 chưa xác thực, 403 cấm, 404 not found, 405 method, 409 conflict, 413 quá lớn, 429 rate limit
5xxLỗi server500 internal, 502 bad gateway, 503 unavailable, 504 gateway timeout

Ở góc nhìn vận hành, 502/503/504 từ proxy hầu như luôn chỉ về upstream, không phải bản thân proxy: 502 = upstream trả rác hoặc từ chối, 503 = không có upstream khỏe / quá tải, 504 = upstream quá chậm.

Phiên bảnTransportĐặc tính chínhĐiểm yếu
HTTP/1.1TCPMỗi connection một request tại một thời điểm (keep-alive tái dùng socket)Head-of-line blocking; browser mở 6 kết nối mỗi host
HTTP/2TCP + TLSMultiplex nhiều stream trên một kết nối, nén header (HPACK), server pushVẫn bị head-of-line blocking ở tầng TCP khi mất gói
HTTP/3QUIC (UDP) + TLS 1.3Stream độc lập (mất gói ở stream này không chặn stream khác), handshake 1-RTT (hoặc 0-RTT), connection migration khi đổi mạngUDP đôi khi bị middlebox bóp/chặn
curl -v https://example.com/api/health           # xem toàn bộ trao đổi (DNS, TLS, header)
curl -I --http2 https://example.com              # chỉ lấy header, thương lượng h2
curl -w '%{time_namelookup} %{time_connect} %{time_starttransfer} %{time_total}\n' \
     -o /dev/null -s https://example.com          # bóc tách độ trễ theo từng pha
curl --resolve example.com:443:10.0.1.5 https://example.com/  # bỏ qua DNS để test một backend

Khái niệm chính

TLS/SSL

TLS cung cấp mã hóa (tính bí mật), toàn vẹn (phát hiện giả mạo) và xác thực (chứng minh server, và tùy chọn cả client, đúng là bên họ tuyên bố). “SSL” chỉ còn là cách gọi quen miệng — SSLv2/v3 và TLS 1.0/1.1 đã bị loại bỏ và không an toàn; dùng tối thiểu TLS 1.2, ưu tiên TLS 1.3.

Handshake TLS 1.3 (1-RTT): client gửi ClientHello kèm key share và các cipher hỗ trợ → server trả ServerHello, certificate và key share → hai bên dẫn xuất cùng session key qua (EC)DHE → dữ liệu ứng dụng được mã hóa. TLS 1.3 bỏ được một vòng round trip so với 1.2 và loại các cipher yếu; 0-RTT resumption có thể gửi dữ liệu ngay gói đầu tiên (đánh đổi bằng rủi ro replay với request không idempotent).

Chuỗi certificate (leaf → intermediate → root CA tin cậy) chứng minh danh tính. Client kiểm tra: hostname với các mục SAN trong certificate (trường CN đã lỗi thời cho việc này), thời hạn hiệu lực, chữ ký lên tới một root tin cậy, và trạng thái thu hồi (OCSP/OCSP stapling hoặc CRL). mTLS (mutual TLS) bắt cả client trình certificate — nền tảng của service mesh zero-trust.

Let’s Encrypt cấp certificate miễn phí thời hạn 90 ngày qua giao thức ACME; các công cụ như certbot hoặc Caddy tự động gia hạn. Loại challenge: HTTP-01 (phục vụ token trên port 80 — đơn giản, không hỗ trợ wildcard), DNS-01 (tạo bản ghi TXT — bắt buộc cho wildcard, hoạt động sau firewall), TLS-ALPN-01 (trên port 443).

# Kiểm tra chuỗi certificate đang chạy, subject, issuer và thời hạn
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

# Kiểm tra protocol/cipher đã thương lượng
openssl s_client -connect example.com:443 -tls1_3 </dev/null 2>/dev/null | grep -E 'Protocol|Cipher'

# Cấp/gia hạn bằng certbot (plugin nginx)
sudo certbot --nginx -d example.com -d www.example.com

Lỗi TLS thường gặp: certificate hết hạn, hostname không khớp (cert không cover SAN bạn yêu cầu), chuỗi không đầy đủ (thiếu intermediate — chạy được trong browser đã cache nó, nhưng fail trong curl/Java), và lệch đồng hồ khiến cert hợp lệ trông như chưa có hiệu lực.

SSH

SSH cung cấp remote shell mã hóa, truyền file và tunnel. Ưu tiên xác thực bằng key (Ed25519 > RSA-2048+) và tắt hoàn toàn đăng nhập bằng mật khẩu.

ssh-keygen -t ed25519 -C "nam@laptop"    # tạo cặp key
ssh-copy-id user@server                  # cài public key lên server
ssh -v user@server                       # verbose: debug lỗi auth/handshake

Xác minh host key (dòng “authenticity of host can’t be established”) là một kiểm soát bảo mật thật — nó chống man-in-the-middle bằng cách ghim key của server vào ~/.ssh/known_hosts. Quản lý ở quy mô lớn bằng signed host certificate hoặc phân phối known-hosts.

# ~/.ssh/config — profile kết nối khai báo
Host bastion
    HostName bastion.example.com
    User ops
    IdentityFile ~/.ssh/id_ed25519

Host app-*
    ProxyJump bastion          # đi qua bastion một cách trong suốt
    User deploy
    IdentitiesOnly yes

Tunneling (một trong những siêu năng lực của SSH):

ssh -L 5432:db.internal:5432 bastion   # local forward: localhost:5432 -> db.internal:5432
ssh -R 8080:localhost:3000 vps         # remote forward: đưa app local ra VPS
ssh -D 1080 bastion                    # SOCKS proxy động (duyệt web qua remote)
ssh -J bastion app-01                  # jump host trong một lệnh

Dùng ssh-agent (với AddKeysToAgent) để không phải gõ lại passphrase của key mỗi lần kết nối, và agent forwarding một cách thận trọng (nó cho host remote dùng key của bạn). Với production, ưu tiên session manager (AWS SSM Session Manager, GCP IAP) để loại bỏ hoàn toàn port 22 mở và bastion công khai.

Truyền file và giao thức email

Firewall, NAT và security group

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 10.0.0.0/16 to any port 22 proto tcp   # SSH chỉ từ VPC
sudo ufw allow 443/tcp                                       # HTTPS từ mọi nơi
sudo ufw enable
sudo ufw status numbered                                    # rà soát ruleset

Cơ bản về load balancing

Load balancer phân phối traffic đến các backend và kiểm tra sức khỏe (health check) để node chết bị loại tự động. L4 định tuyến theo IP/port (nhanh, không phụ thuộc giao thức, TLS passthrough); L7 hiểu HTTP và có thể routing theo path/host/header, terminate TLS, retry và rewrite. Thuật toán phổ biến: round robin, weighted round robin, least connections, và IP hash / consistent hashing để giữ session affinity. Chi tiết hơn — thuật toán, L4 vs L7, config mẫu — ở chủ đề 06 (Web Server, Proxy & Load Balancer).

Mô hình debug theo tầng

Kỹ năng networking giá trị nhất là khoanh vùng tầng nào đang hỏng, từ dưới lên:

  1. L1/L2/L3 — khả năng tiếp cận: ping host (ICMP). Fail? Kiểm tra route (ip route), subnet, và security group.
  2. DNS — đặt tên: dig +short name. Trả kết quả sai/rỗng? Đó là lỗi DNS hoặc bản ghi, không phải app.
  3. L4 — port: nc -zv host 443 hoặc ss -tlnp trên server. Refused = không có gì lắng nghe; timeout = firewall đang drop.
  4. TLS — handshake: openssl s_client -connect host:443. Lỗi cert hoặc protocol lộ ra ở đây.
  5. L7 — ứng dụng: curl -v https://host/path. Giờ bạn đang đọc status code và header.

Mỗi bước loại trừ mọi tầng bên dưới nó, biến “site sập” thành một chẩn đoán chính xác trong năm phút.

Best Practices

  1. Debug từ tầng thấp lên cao — kiểm tra kết nối L3 (ping), rồi DNS (dig), rồi port (nc -zv host 443), rồi TLS (openssl s_client), rồi app (curl -v). Cách này khoanh vùng tầng lỗi trong vài phút thay vì đoán mò.
  2. Quy hoạch dải CIDR trước khi xây — dải VPC/VPN/văn phòng chồng lấn nhau sửa về sau rất đau và đôi khi bất khả thi (không thể route giữa hai 10.0.0.0/16). Dành sẵn các block không trùng cho từng môi trường và region ngay từ đầu, chừa chỗ để mở rộng.
  3. Đặt TTL DNS có chủ đích — TTL thấp (60s) trước khi migrate và cho bản ghi failover; TTL cao (1h+) cho bản ghi ổn định để giảm tải resolver và độ trễ. Hạ TTL trước khi thay đổi, không phải trong lúc đang đổi.
  4. TLS ở mọi nơi, tối thiểu TLS 1.2, ưu tiên 1.3 — kể cả traffic nội bộ giữa các service (hoặc mTLS qua service mesh). Sinh config bằng Mozilla SSL Config Generator và chấm điểm bằng SSL Labs.
  5. Tự động hóa cấp và gia hạn certificate — ACME/Let’s Encrypt với certbot hoặc Caddy, hoặc cert do cloud quản lý (ACM, GCP-managed). Cảnh báo khi cert còn 14–30 ngày; cert hết hạn vẫn là một trong những sự cố tự gây ra phổ biến nhất.
  6. Tắt xác thực mật khẩu và đăng nhập root qua SSH — chỉ dùng key (Ed25519), và ưu tiên session manager (SSM/IAP) hoặc bastion thay vì mở port 22 ra internet. Rotate và kiểm kê key.
  7. Firewall theo nguyên tắc default-deny — chỉ mở port cần thiết, giới hạn nguồn bằng tham chiếu security group hoặc CIDR hẹp, siết egress ở nơi cần, và rà soát rule định kỳ để phát hiện drift.
  8. Dùng SFTP / rsync-over-SSH, tuyệt đối không dùng FTP thuần — credential truyền plaintext là không thể chấp nhận; nếu buộc phải tương tác với FTP, tối thiểu dùng FTPS.
  9. Thuộc lòng HTTP status code và đặt cache header đúng — 502/503/504 chỉ hướng điều tra về upstream; Cache-Control, ETagLast-Modified giảm tải origin đáng kể và cho phép trả 304.
  10. Bật HSTS và redirect HTTP→HTTPSStrict-Transport-Security: max-age=31536000; includeSubDomains chặn tấn công hạ cấp giao thức sau lần truy cập đầu; cân nhắc HSTS preloading cho domain nhạy cảm.
  11. Giám sát DNS và TLS như tín hiệu hạng nhất — lỗi phân giải, đột biến NXDOMAIN, lỗi handshake và đếm ngược hết hạn cert thường xuất hiện trước báo cáo “app sập” hàng giờ.
  12. Chọn đúng MTU cho overlay và VPN — MTU lệch gây treo phụ thuộc kích thước payload; bật PMTUD hoặc hạ MTU interface (ví dụ 1400) trên tunnel.
  13. Ưu tiên private subnet với NAT cho egress — tầng app và data không nên có IP public; cho chúng ra ngoài qua NAT gateway và chỉ nhận vào qua load balancer.
  14. Học công cụ bắt gói tintcpdump -i any port 443 -w cap.pcap cùng Wireshark, và mtr/ss, trả lời được những câu hỏi mà log và metric không thể.

Tài liệu tham khảo

Part of the DevOps Roadmap knowledge base.

Overview

Networking is the substrate every distributed system runs on. Whether you are debugging why a pod can’t reach a database, terminating TLS at a load balancer, or writing a security group rule, you are working with the same handful of protocols: IP, TCP/UDP, DNS, HTTP, and TLS. A DevOps engineer who understands these layers can reason about failures precisely (“is this a DNS problem, a routing problem, or an application problem?”) instead of guessing — which is the difference between a five-minute fix and a two-hour outage.

The classic mental models are the OSI 7-layer model and the practical 4-layer TCP/IP stack. OSI is a teaching and vocabulary tool (“L4 load balancer”, “L7 firewall”); TCP/IP is what real networks implement. On top of these sit the application protocols you touch daily: DNS for naming, HTTP(S) for almost all service traffic, TLS for encryption and identity, and SSH for administration.

Cloud infrastructure makes networking programmable — VPCs, subnets, route tables, NAT gateways, security groups — but the underlying concepts are unchanged. Mastering CIDR math, DNS resolution, and the TLS handshake pays off across every cloud and every on-prem environment. The goal of this page is to give you enough of a model that packet-level tools (dig, curl -v, tcpdump) become a conversation with the network rather than an incantation.

Fundamentals

OSI model vs TCP/IP stack

OSI layerNameTCP/IP layerExamplesWhat breaks here
7ApplicationApplicationHTTP, DNS, SSH, SMTPBad request, 5xx, auth
6PresentationApplicationTLS (loosely), serializationCert/handshake errors
5SessionApplicationSession handlingSession/state loss
4TransportTransportTCP, UDP, QUICPort closed, RST, timeout
3NetworkInternetIP, ICMP, routingNo route, wrong subnet
2Data LinkLinkEthernet, ARP, Wi-FiARP, MTU, VLAN
1PhysicalLinkCables, radioCable/NIC down

In practice engineers use OSI numbers as vocabulary (“L4 vs L7 load balancing”) while real stacks behave like TCP/IP. Each layer wraps the one above it in a header (encapsulation): an HTTP request becomes a TCP segment, inside an IP packet, inside an Ethernet frame.

TCP vs UDP — the two transport protocols you meet constantly:

TCPUDP
ConnectionConnection-oriented (3-way handshake: SYN → SYN-ACK → ACK)Connectionless — fire and forget
ReliabilityOrdered, retransmitted, acknowledgedNone — app handles loss if it cares
Flow/congestion controlYesNo
Overhead / latencyHigher (handshake, ACKs)Lower
Used byHTTP/1–2, SSH, SMTP, most APIsDNS, DHCP, NTP, QUIC/HTTP/3, VoIP, streaming

A TCP connection ends with a FIN handshake; an abrupt RST means “no one is listening” or “connection forcibly closed” — a very common signal when a port is closed or an app crashed. MTU (typically 1500 bytes) matters: packets larger than the path MTU are fragmented or dropped, and mismatched MTU (common with VPN/overlay networks) causes mysterious hangs on large payloads.

IP addressing, subnets, and CIDR

CIDR notation 10.0.0.0/16 means the first 16 bits are the network prefix, leaving 2^16 = 65,536 addresses. The prefix length is the number of leading 1 bits in the subnet mask.

CIDRMaskAddressesTypical use
/8255.0.0.016,777,216Huge private range (10.0.0.0/8)
/16255.255.0.065,536A whole VPC
/20255.255.240.04,096Large subnet / AZ
/24255.255.255.0256 (254 usable)Standard subnet
/28255.255.255.24016Small subnet (bastions, endpoints)
/32255.255.255.2551A single host (security group rules)

Key facts:

NAT (Network Address Translation) lets private addresses share public IPs. A NAT gateway gives private subnets outbound internet access (for updates, API calls) without exposing them to inbound connections — a cornerstone of the “private subnet” pattern where app and DB tiers have no public IP at all.

ip addr                          # interfaces and addresses
ip route                         # routing table (which next-hop for which prefix)
ping -c 3 8.8.8.8                # L3 reachability
traceroute example.com           # path discovery, hop by hop
mtr example.com                  # continuous traceroute + loss stats
ss -tlnp                         # listening TCP sockets and owning processes
nc -zv host 443                  # is the port open? (L4 probe)
ipcalc 10.0.0.0/20               # subnet math helper

DNS

DNS translates names to records — it is the phone book of the internet, and it is behind a surprising share of outages (“it’s always DNS”).

Resolution flow: stub resolver (your OS) → recursive resolver (e.g. 1.1.1.1, 8.8.8.8, or the VPC resolver) → root servers (.) → TLD servers (.com) → authoritative servers for the zone → answer, cached at each hop according to TTL.

RecordPurpose
A / AAAAName → IPv4 / IPv6 address
CNAMEAlias to another name (not allowed at the zone apex)
ALIAS / ANAMEApex-safe “CNAME-like” (provider-specific: Route 53 alias, etc.)
MXMail server for the domain (with priority)
TXTArbitrary text — SPF, DKIM, DMARC, domain verification
NSDelegates a zone to name servers
SOAZone metadata (primary NS, serial, refresh/retry/expire timers)
SRVService location (protocol, port, host)
PTRReverse lookup (IP → name), used by mail reputation
CAAWhich CAs may issue certificates for the domain
dig +short example.com A
dig example.com MX @1.1.1.1      # query a specific resolver
dig +trace example.com           # follow the full delegation chain from the root
dig -x 1.1.1.1                   # reverse (PTR) lookup
host example.com                 # quick lookup
resolvectl status                # what resolvers is this host actually using?

TTL is a trade-off: low TTL (60s) means fast propagation and quick failover but more query load and latency; high TTL (hours) means efficient caching but slow changes. Lower TTL before a planned migration, then raise it after.

In infrastructure, DNS is also a traffic-management tool: weighted, latency-based, geolocation, and failover routing (Route 53, Cloudflare, NS1), and service discovery (Consul, Kubernetes CoreDNS resolving service.namespace.svc.cluster.local). Modern privacy variants DoH (DNS over HTTPS) and DoT (DNS over TLS) encrypt queries that were historically plaintext.

HTTP and HTTPS

ClassMeaningKey codes
2xxSuccess200 OK, 201 Created, 204 No Content, 206 Partial
3xxRedirect301 permanent, 302/307 temporary, 304 Not Modified (cache)
4xxClient error400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 405 method, 409 conflict, 413 too large, 429 rate limited
5xxServer error500 internal, 502 bad gateway, 503 unavailable, 504 gateway timeout

As an operator, 502/503/504 from a proxy almost always point at the upstream, not the proxy itself: 502 = upstream returned garbage or refused, 503 = no healthy upstream / overloaded, 504 = upstream too slow.

VersionTransportKey propertyWeakness
HTTP/1.1TCPOne request at a time per connection (keep-alive reuses the socket)Head-of-line blocking; browsers open 6 connections per host
HTTP/2TCP + TLSMultiplexed streams on one connection, header compression (HPACK), server pushStill suffers TCP-level head-of-line blocking on packet loss
HTTP/3QUIC (UDP) + TLS 1.3Independent streams (loss on one doesn’t stall others), 1-RTT (or 0-RTT) handshake, connection migration across network changesUDP sometimes throttled/blocked by middleboxes
curl -v https://example.com/api/health           # inspect the full exchange (DNS, TLS, headers)
curl -I --http2 https://example.com              # headers only, negotiate h2
curl -w '%{time_namelookup} %{time_connect} %{time_starttransfer} %{time_total}\n' \
     -o /dev/null -s https://example.com          # latency breakdown per phase
curl --resolve example.com:443:10.0.1.5 https://example.com/  # bypass DNS to test one backend

Key Concepts

TLS/SSL

TLS provides encryption (confidentiality), integrity (tamper detection), and authentication (proving the server, and optionally the client, is who it claims). “SSL” survives only as a colloquial name — SSLv2/v3 and TLS 1.0/1.1 are deprecated and insecure; use TLS 1.2 as a floor and prefer TLS 1.3.

TLS 1.3 handshake (1-RTT): client sends ClientHello with its key share and supported ciphers → server replies with ServerHello, its certificate, and key share → both derive the same session keys via (EC)DHE → encrypted application data flows. TLS 1.3 dropped a full round trip versus 1.2 and removed weak ciphers; 0-RTT resumption can send data on the first packet (at the cost of replay risk for non-idempotent requests).

The certificate chain (leaf → intermediate → trusted root CA) proves identity. The client validates: the hostname against the certificate’s SAN entries (the CN field is obsolete for this), the validity dates, the signature up to a trusted root, and revocation (OCSP/OCSP stapling or CRLs). mTLS (mutual TLS) additionally makes the client present a certificate — the basis of zero-trust service meshes.

Let’s Encrypt issues free 90-day certificates via the ACME protocol; tools like certbot or Caddy renew them automatically. Challenge types: HTTP-01 (serve a token on port 80 — simple, no wildcards), DNS-01 (create a TXT record — required for wildcard certs, works behind firewalls), TLS-ALPN-01 (on port 443).

# Inspect a live certificate chain, subject, issuer, and validity
openssl s_client -connect example.com:443 -servername example.com </dev/null 2>/dev/null \
  | openssl x509 -noout -subject -issuer -dates -ext subjectAltName

# Check the negotiated protocol/cipher
openssl s_client -connect example.com:443 -tls1_3 </dev/null 2>/dev/null | grep -E 'Protocol|Cipher'

# Issue/renew with certbot (nginx plugin)
sudo certbot --nginx -d example.com -d www.example.com

Common TLS failures: expired certificate, hostname mismatch (cert doesn’t cover the SAN you requested), incomplete chain (missing intermediate — works in browsers that cache it, fails in curl/Java), and clock skew making a valid cert look not-yet-valid.

SSH

SSH gives encrypted remote shells, file transfer, and tunnels. Prefer key-based auth (Ed25519 > RSA-2048+) and disable password login entirely.

ssh-keygen -t ed25519 -C "nam@laptop"    # generate a key pair
ssh-copy-id user@server                  # install your public key on the server
ssh -v user@server                       # verbose: debug auth/handshake problems

Host key verification (the “authenticity of host can’t be established” prompt) is a real security control — it defeats man-in-the-middle attacks by pinning the server’s key in ~/.ssh/known_hosts. Manage it at scale with signed host certificates or a known-hosts distribution.

# ~/.ssh/config — declarative connection profiles
Host bastion
    HostName bastion.example.com
    User ops
    IdentityFile ~/.ssh/id_ed25519

Host app-*
    ProxyJump bastion          # transparently hop through the bastion
    User deploy
    IdentitiesOnly yes

Tunneling (one of SSH’s superpowers):

ssh -L 5432:db.internal:5432 bastion   # local forward: localhost:5432 -> db.internal:5432
ssh -R 8080:localhost:3000 vps         # remote forward: expose a local app on the VPS
ssh -D 1080 bastion                    # dynamic SOCKS proxy (browse via the remote)
ssh -J bastion app-01                  # jump host in one command

Use an ssh-agent (with AddKeysToAgent) so a passphrase-protected key isn’t retyped every connection, and agent forwarding cautiously (it lets the remote host use your keys). For production, prefer session managers (AWS SSM Session Manager, GCP IAP) that eliminate open port 22 and public bastions entirely.

File transfer and email protocols

Firewalls, NAT, and security groups

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow from 10.0.0.0/16 to any port 22 proto tcp   # SSH only from the VPC
sudo ufw allow 443/tcp                                       # HTTPS from anywhere
sudo ufw enable
sudo ufw status numbered                                    # audit the ruleset

Load balancing basics

A load balancer distributes traffic across backends and health-checks them so dead nodes are removed automatically. L4 balancers route by IP/port (fast, protocol-agnostic, TLS passthrough); L7 balancers understand HTTP and can route by path/host/header, terminate TLS, retry, and rewrite. Common algorithms: round robin, weighted round robin, least connections, and IP hash / consistent hashing for session affinity. Deeper coverage — algorithms, L4 vs L7, sample configs — is in topic 06 (Web Servers, Proxies & Load Balancers).

A layered debugging model

The single most valuable networking skill is isolating which layer is broken, bottom-up:

  1. L1/L2/L3 — reachability: ping host (ICMP). Fails? Check routes (ip route), the subnet, and security groups.
  2. DNS — naming: dig +short name. Wrong/empty answer? It’s a DNS or record problem, not the app.
  3. L4 — the port: nc -zv host 443 or ss -tlnp on the server. Refused = nothing listening; timeout = firewall dropping.
  4. TLS — the handshake: openssl s_client -connect host:443. Cert or protocol error surfaces here.
  5. L7 — the application: curl -v https://host/path. Now you’re reading status codes and headers.

Each step rules out everything below it, turning “the site is down” into a precise, five-minute diagnosis.

Best Practices

  1. Debug bottom-up through the layers — check L3 reachability (ping), then DNS (dig), then the port (nc -zv host 443), then TLS (openssl s_client), then the app (curl -v). This isolates the failing layer in minutes instead of guessing.
  2. Plan CIDR ranges before building — overlapping VPC/VPN/office ranges are painful and sometimes impossible to fix later (you cannot route between two 10.0.0.0/16s). Reserve non-overlapping blocks per environment and region up front, and leave room to grow.
  3. Set DNS TTLs deliberately — low TTL (60s) before migrations and on failover records; higher TTL (1h+) for stable records to reduce resolver load and latency. Lower TTL before the change, not during.
  4. Use TLS everywhere, TLS 1.2 minimum, prefer 1.3 — including internal service-to-service traffic (or mTLS via a service mesh). Generate config with Mozilla’s SSL Config Generator and grade it with SSL Labs.
  5. Automate certificate issuance and renewal — ACME/Let’s Encrypt with certbot or Caddy, or cloud-managed certs (ACM, GCP-managed). Alert on certificates expiring within 14–30 days; an expired cert remains one of the most common self-inflicted outages.
  6. Disable SSH password authentication and root login — keys only (Ed25519), and prefer a session manager (SSM/IAP) or a bastion over exposing port 22 to the internet. Rotate and inventory keys.
  7. Adopt a default-deny firewall posture — open only required ports, restrict sources by security-group reference or tight CIDR, tighten egress where it matters, and review rules regularly for drift.
  8. Prefer SFTP / rsync-over-SSH, never plain FTP — plaintext credentials on the wire are indefensible; if you must interoperate with FTP, use FTPS at minimum.
  9. Know your HTTP status codes and set correct cache headers — 502/503/504 triage points at upstreams; Cache-Control, ETag, and Last-Modified cut origin load dramatically and enable 304s.
  10. Send HSTS and redirect HTTP→HTTPSStrict-Transport-Security: max-age=31536000; includeSubDomains prevents protocol-downgrade attacks after the first visit; consider HSTS preloading for sensitive domains.
  11. Monitor DNS and TLS as first-class signals — resolution failures, NXDOMAIN spikes, handshake errors, and cert-expiry countdowns often precede “the app is down” reports by hours.
  12. Right-size MTU on overlays and VPNs — mismatched MTU causes payload-size-dependent hangs; enable PMTUD or lower the interface MTU (e.g. 1400) on tunnels.
  13. Prefer private subnets with NAT for egress — app and data tiers should have no public IP; give them outbound access via a NAT gateway and inbound only through the load balancer.
  14. Learn the capture toolstcpdump -i any port 443 -w cap.pcap plus Wireshark, and mtr/ss, answer questions that logs and metrics cannot.

References