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 OSI | Tên | Tầng TCP/IP | Ví dụ | Hỏng ở đây là gì |
|---|---|---|---|---|
| 7 | Application | Application | HTTP, DNS, SSH, SMTP | Request sai, 5xx, auth |
| 6 | Presentation | Application | TLS (tương đối), serialization | Lỗi cert/handshake |
| 5 | Session | Application | Quản lý session | Mất session/state |
| 4 | Transport | Transport | TCP, UDP, QUIC | Port đóng, RST, timeout |
| 3 | Network | Internet | IP, ICMP, routing | Không có route, sai subnet |
| 2 | Data Link | Link | Ethernet, ARP, Wi-Fi | ARP, MTU, VLAN |
| 1 | Physical | Link | Cá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:
| TCP | UDP | |
|---|---|---|
| Kết nối | Hướ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ậy | Có thứ tự, truyền lại, có ACK | Không có — app tự xử lý mất gói nếu cần |
| Flow/congestion control | Có | Không |
| Overhead / độ trễ | Cao hơn (handshake, ACK) | Thấp hơn |
| Được dùng bởi | HTTP/1–2, SSH, SMTP, hầu hết API | DNS, 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.
| CIDR | Mask | Số địa chỉ | Dùng điển hình |
|---|---|---|---|
/8 | 255.0.0.0 | 16.777.216 | Dải private khổng lồ (10.0.0.0/8) |
/16 | 255.255.0.0 | 65.536 | Cả một VPC |
/20 | 255.255.240.0 | 4.096 | Subnet lớn / AZ |
/24 | 255.255.255.0 | 256 (254 dùng được) | Subnet tiêu chuẩn |
/28 | 255.255.255.240 | 16 | Subnet nhỏ (bastion, endpoint) |
/32 | 255.255.255.255 | 1 | Một host đơn (rule security group) |
Điểm cần nhớ:
- Trên mạng truyền thống,
/24có 254 địa chỉ dùng được (địa chỉ network.0và broadcast.255được giữ lại). Cloud provider giữ thêm địa chỉ — AWS giữ 5 địa chỉ mỗi subnet (network, VPC router, DNS, dự phòng, broadcast), nên/24chỉ còn 251 dùng được. - Dải private (RFC 1918):
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16. Cũng hữu ích:100.64.0.0/10(carrier-grade NAT, vài cloud/VPN dùng) và169.254.0.0/16(link-local, metadata cloud tại169.254.169.254). - Subnetting: chia một block lớn thành các block nhỏ hơn. Tăng prefix một bậc (ví dụ
/24→ hai/25) nhân đôi số subnet và giảm nửa số host mỗi subnet. - Thiết kế VPC điển hình: một VPC
/16chia thành các subnet/20hoặc/24, một nhóm public và một nhóm private cho mỗi availability zone để đạt độ sẵn sàng cao. - IPv6 loại bỏ vấn đề khan hiếm (địa chỉ 128 bit, chuẩn
/64mỗi subnet) và không cần NAT; triển khai dual-stack ngày càng phổ biến.
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 ghi | Mục đích |
|---|---|
| A / AAAA | Tên → địa chỉ IPv4 / IPv6 |
| CNAME | Alias 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.) |
| MX | Mail server của domain (kèm priority) |
| TXT | Văn bản tùy ý — SPF, DKIM, DMARC, xác minh domain |
| NS | Ủy quyền zone cho name server |
| SOA | Metadata của zone (primary NS, serial, timer refresh/retry/expire) |
| SRV | Vị trí service (protocol, port, host) |
| PTR | Tra cứu ngược (IP → tên), dùng cho uy tín mail |
| CAA | CA 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
- Method: GET (đọc, safe, idempotent), POST (tạo/hành động, không idempotent), PUT (thay thế, idempotent), PATCH (cập nhật một phần), DELETE (idempotent), HEAD (chỉ header), OPTIONS (khả năng/CORS preflight). Idempotent nghĩa là lặp lại request cho cùng kết quả — đó là lý do proxy có thể an toàn retry GET/PUT nhưng không retry POST.
- Status code phải thuộc lòng:
| Nhóm | Ý nghĩa | Code quan trọng |
|---|---|---|
| 2xx | Thành công | 200 OK, 201 Created, 204 No Content, 206 Partial |
| 3xx | Redirect | 301 vĩnh viễn, 302/307 tạm thời, 304 Not Modified (cache) |
| 4xx | Lỗi client | 400 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 |
| 5xx | Lỗi server | 500 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.
- Header quan trọng khi vận hành:
Host(virtual hosting / routing),Content-Type,Authorization,Cache-Control/ETag/Last-Modified(caching),X-Forwarded-For/X-Forwarded-Proto/Forwarded(client thật phía sau proxy),Strict-Transport-Security(ép HTTPS),Content-Encoding(nén gzip/br),Connection/Keep-Alive. - Các phiên bản giao thức:
| Phiên bản | Transport | Đặc tính chính | Điểm yếu |
|---|---|---|---|
| HTTP/1.1 | TCP | Mỗ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/2 | TCP + TLS | Multiplex nhiều stream trên một kết nối, nén header (HPACK), server push | Vẫn bị head-of-line blocking ở tầng TCP khi mất gói |
| HTTP/3 | QUIC (UDP) + TLS 1.3 | Stream độ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ạng | UDP đô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
- FTP (port điều khiển 21, dữ liệu trên 20 hoặc các port cao ở chế độ passive) là công nghệ cũ, truyền plaintext — nên tránh. FTPS thêm TLS cho FTP nhưng vẫn giữ mô hình hai port khó chịu. SFTP (chạy trên SSH, port 22) là một giao thức hoàn toàn khác và là lựa chọn mặc định hiện đại; ngoài ra có
scp(cũ, đang được thay bằng transfer dựa trên SFTP) vàrsync -e sshđể đồng bộ delta hiệu quả. - Bộ ba email: SMTP gửi mail (port 25 giữa các server, 587 submission có xác thực với STARTTLS, 465 TLS ngầm định). IMAP (993, TLS) đọc mail và giữ lại trên server, đồng bộ trạng thái giữa các thiết bị. POP3 (995, TLS) tải về và thường xóa — hầu như đã lỗi thời.
- Liên quan DevOps của email: SPF (bản ghi TXT liệt kê ai được gửi thay domain bạn), DKIM (chữ ký mật mã), và DMARC (policy + báo cáo, ràng buộc SPF/DKIM với địa chỉ From hiển thị) là thứ giữ mail giao dịch của bạn khỏi spam. Lưu ý cloud mặc định chặn outbound port 25 để chống spam — dùng nhà cung cấp (SES, SendGrid, Postmark) qua 587/API thay vì tự chạy MTA.
Firewall, NAT và security group
- Stateful firewall theo dõi trạng thái kết nối: cho phép inbound 443 thì gói trả lời tự động được cho qua mà không cần rule riêng. Security group trên cloud là allow list stateful ở mức instance/ENI (không có rule deny — thứ gì không được allow là bị chặn). Network ACL là stateless (phải allow cả hai chiều, kể cả port ephemeral trả về) và hoạt động ở mức subnet như một lớp thứ hai thô.
- Firewall trên host:
iptables(cũ),nftables(kế nhiệm),ufw(front-end đơn giản),firewalld(theo zone). Trong Kubernetes, NetworkPolicy đóng vai trò tương tự giữa các pod. - Tư thế mặc định: chặn mọi chiều vào, chỉ mở port cần thiết từ nguồn cụ thể (ưu tiên tham chiếu security group khác hơn là dùng CIDR rộng), và mở chiều ra theo nhu cầu (siết egress trong môi trường bảo mật cao để chống rò rỉ dữ liệu).
- Rule dựa trên tham chiếu tốt hơn rule CIDR trên cloud: “cho phép security group của load balancer chạm tới instance app trên 8080” vẫn đúng khi IP đổi và auto-scaling.
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:
- L1/L2/L3 — khả năng tiếp cận:
ping host(ICMP). Fail? Kiểm tra route (ip route), subnet, và security group. - 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. - L4 — port:
nc -zv host 443hoặcss -tlnptrên server. Refused = không có gì lắng nghe; timeout = firewall đang drop. - TLS — handshake:
openssl s_client -connect host:443. Lỗi cert hoặc protocol lộ ra ở đây. - 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
- 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ò. - 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. - Đặ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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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,ETagvàLast-Modifiedgiảm tải origin đáng kể và cho phép trả 304. - Bật HSTS và redirect HTTP→HTTPS —
Strict-Transport-Security: max-age=31536000; includeSubDomainschặ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. - 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ờ.
- 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.
- Ư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.
- Học công cụ bắt gói tin —
tcpdump -i any port 443 -w cap.pcapcù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
- roadmap.sh DevOps roadmap: https://roadmap.sh/devops
- MDN — Tài liệu HTTP: https://developer.mozilla.org/en-US/docs/Web/HTTP
- MDN — Tham chiếu HTTP status code: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- Cloudflare Learning Center (DNS, TLS, QUIC, load balancing): https://www.cloudflare.com/learning/
- Let’s Encrypt — How it works: https://letsencrypt.org/how-it-works/
- Mozilla SSL Configuration Generator: https://ssl-config.mozilla.org/
- Qualys SSL Labs — server test: https://www.ssllabs.com/ssltest/
- Trang manual của OpenSSH: https://www.openssh.com/manual.html
- RFC 9110 — HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110
- RFC 9112 — HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112
- RFC 9113 — HTTP/2: https://www.rfc-editor.org/rfc/rfc9113
- RFC 9114 — HTTP/3: https://www.rfc-editor.org/rfc/rfc9114
- RFC 9000 — QUIC transport: https://www.rfc-editor.org/rfc/rfc9000
- RFC 8446 — TLS 1.3: https://www.rfc-editor.org/rfc/rfc8446
- RFC 1918 — Cấp phát địa chỉ private: https://www.rfc-editor.org/rfc/rfc1918
- RFC 1035 — Domain names (DNS): https://www.rfc-editor.org/rfc/rfc1035
- Julia Evans — zine về networking: https://wizardzines.com/
- Sách: “Computer Networking: A Top-Down Approach” — Kurose & Ross
- Sách: “TCP/IP Illustrated, Vol. 1” — W. Richard Stevens
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 layer | Name | TCP/IP layer | Examples | What breaks here |
|---|---|---|---|---|
| 7 | Application | Application | HTTP, DNS, SSH, SMTP | Bad request, 5xx, auth |
| 6 | Presentation | Application | TLS (loosely), serialization | Cert/handshake errors |
| 5 | Session | Application | Session handling | Session/state loss |
| 4 | Transport | Transport | TCP, UDP, QUIC | Port closed, RST, timeout |
| 3 | Network | Internet | IP, ICMP, routing | No route, wrong subnet |
| 2 | Data Link | Link | Ethernet, ARP, Wi-Fi | ARP, MTU, VLAN |
| 1 | Physical | Link | Cables, radio | Cable/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:
| TCP | UDP | |
|---|---|---|
| Connection | Connection-oriented (3-way handshake: SYN → SYN-ACK → ACK) | Connectionless — fire and forget |
| Reliability | Ordered, retransmitted, acknowledged | None — app handles loss if it cares |
| Flow/congestion control | Yes | No |
| Overhead / latency | Higher (handshake, ACKs) | Lower |
| Used by | HTTP/1–2, SSH, SMTP, most APIs | DNS, 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.
| CIDR | Mask | Addresses | Typical use |
|---|---|---|---|
/8 | 255.0.0.0 | 16,777,216 | Huge private range (10.0.0.0/8) |
/16 | 255.255.0.0 | 65,536 | A whole VPC |
/20 | 255.255.240.0 | 4,096 | Large subnet / AZ |
/24 | 255.255.255.0 | 256 (254 usable) | Standard subnet |
/28 | 255.255.255.240 | 16 | Small subnet (bastions, endpoints) |
/32 | 255.255.255.255 | 1 | A single host (security group rules) |
Key facts:
- On traditional networks a
/24has 254 usable addresses (network address.0and broadcast.255are reserved). Cloud providers reserve extra addresses — AWS reserves 5 per subnet (network, VPC router, DNS, future use, broadcast), so a/24gives 251 usable. - Private ranges (RFC 1918):
10.0.0.0/8,172.16.0.0/12,192.168.0.0/16. Also useful:100.64.0.0/10(carrier-grade NAT, used by some clouds/VPNs) and169.254.0.0/16(link-local, cloud metadata at169.254.169.254). - Subnetting: splitting a larger block into smaller ones. Halving a prefix (e.g.
/24→ two/25s) doubles the number of subnets and halves the hosts each. - Typical VPC design: a
/16VPC split into/20or/24subnets, one set of public and one set of private subnets per availability zone for high availability. - IPv6 removes the scarcity problem (128-bit addresses,
/64per subnet is standard) and eliminates the need for NAT; dual-stack deployments are increasingly common.
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.
| Record | Purpose |
|---|---|
| A / AAAA | Name → IPv4 / IPv6 address |
| CNAME | Alias to another name (not allowed at the zone apex) |
| ALIAS / ANAME | Apex-safe “CNAME-like” (provider-specific: Route 53 alias, etc.) |
| MX | Mail server for the domain (with priority) |
| TXT | Arbitrary text — SPF, DKIM, DMARC, domain verification |
| NS | Delegates a zone to name servers |
| SOA | Zone metadata (primary NS, serial, refresh/retry/expire timers) |
| SRV | Service location (protocol, port, host) |
| PTR | Reverse lookup (IP → name), used by mail reputation |
| CAA | Which 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
- Methods: GET (read, safe, idempotent), POST (create/action, not idempotent), PUT (replace, idempotent), PATCH (partial update), DELETE (idempotent), HEAD (headers only), OPTIONS (capabilities/CORS preflight). Idempotent means repeating the request has the same effect — which is why proxies may safely retry GET/PUT but not POST.
- Status codes you must know cold:
| Class | Meaning | Key codes |
|---|---|---|
| 2xx | Success | 200 OK, 201 Created, 204 No Content, 206 Partial |
| 3xx | Redirect | 301 permanent, 302/307 temporary, 304 Not Modified (cache) |
| 4xx | Client error | 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 405 method, 409 conflict, 413 too large, 429 rate limited |
| 5xx | Server error | 500 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.
- Headers that matter in ops:
Host(virtual hosting / routing),Content-Type,Authorization,Cache-Control/ETag/Last-Modified(caching),X-Forwarded-For/X-Forwarded-Proto/Forwarded(real client behind a proxy),Strict-Transport-Security(force HTTPS),Content-Encoding(gzip/br compression),Connection/Keep-Alive. - Protocol versions:
| Version | Transport | Key property | Weakness |
|---|---|---|---|
| HTTP/1.1 | TCP | One request at a time per connection (keep-alive reuses the socket) | Head-of-line blocking; browsers open 6 connections per host |
| HTTP/2 | TCP + TLS | Multiplexed streams on one connection, header compression (HPACK), server push | Still suffers TCP-level head-of-line blocking on packet loss |
| HTTP/3 | QUIC (UDP) + TLS 1.3 | Independent streams (loss on one doesn’t stall others), 1-RTT (or 0-RTT) handshake, connection migration across network changes | UDP 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
- FTP (control port 21, data on 20 or passive high ports) is legacy and plaintext — avoid. FTPS adds TLS to FTP but keeps the awkward dual-port model. SFTP (over SSH, port 22) is a completely different protocol and the modern default; also
scp(legacy, being replaced by SFTP-backed transfers) andrsync -e sshfor efficient delta sync. - Email trio: SMTP sends mail (port 25 server-to-server, 587 authenticated submission with STARTTLS, 465 implicit TLS). IMAP (993, TLS) reads mail while leaving it on the server and syncing state across devices. POP3 (995, TLS) downloads and typically deletes — largely obsolete.
- DevOps relevance of email: SPF (TXT record listing who may send for your domain), DKIM (cryptographic signature), and DMARC (policy + reporting tying SPF/DKIM to the visible From) are what keep your transactional mail out of spam. Note that clouds block outbound port 25 by default to fight spam — use a provider (SES, SendGrid, Postmark) over 587/API instead of running your own MTA.
Firewalls, NAT, and security groups
- Stateful firewalls track connection state: allow inbound 443 and the reply packets flow back automatically without a separate rule. Cloud security groups are stateful, instance/ENI-level allow lists (no deny rules — anything not allowed is denied). Network ACLs are stateless (you must allow both directions, including ephemeral return ports) and operate at the subnet level as a coarse second layer.
- Host firewalls:
iptables(legacy),nftables(its successor),ufw(simple front-end),firewalld(zone-based). In Kubernetes, NetworkPolicies play the same role between pods. - Default posture: deny all inbound, explicitly allow only required ports from specific sources (prefer referencing another security group over broad CIDRs), and allow outbound as needed (tighten egress in high-security environments to prevent data exfiltration).
- Reference-based rules beat CIDR rules in the cloud: “allow the load-balancer security group to reach app instances on 8080” survives IP changes and auto-scaling.
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:
- L1/L2/L3 — reachability:
ping host(ICMP). Fails? Check routes (ip route), the subnet, and security groups. - DNS — naming:
dig +short name. Wrong/empty answer? It’s a DNS or record problem, not the app. - L4 — the port:
nc -zv host 443orss -tlnpon the server. Refused = nothing listening; timeout = firewall dropping. - TLS — the handshake:
openssl s_client -connect host:443. Cert or protocol error surfaces here. - 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
- 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. - 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. - 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- Know your HTTP status codes and set correct cache headers — 502/503/504 triage points at upstreams;
Cache-Control,ETag, andLast-Modifiedcut origin load dramatically and enable 304s. - Send HSTS and redirect HTTP→HTTPS —
Strict-Transport-Security: max-age=31536000; includeSubDomainsprevents protocol-downgrade attacks after the first visit; consider HSTS preloading for sensitive domains. - 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.
- 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.
- 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.
- Learn the capture tools —
tcpdump -i any port 443 -w cap.pcapplus Wireshark, andmtr/ss, answer questions that logs and metrics cannot.
References
- roadmap.sh DevOps roadmap: https://roadmap.sh/devops
- MDN — HTTP documentation: https://developer.mozilla.org/en-US/docs/Web/HTTP
- MDN — HTTP status codes reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
- Cloudflare Learning Center (DNS, TLS, QUIC, load balancing): https://www.cloudflare.com/learning/
- Let’s Encrypt — How it works: https://letsencrypt.org/how-it-works/
- Mozilla SSL Configuration Generator: https://ssl-config.mozilla.org/
- Qualys SSL Labs — server test: https://www.ssllabs.com/ssltest/
- OpenSSH manual pages: https://www.openssh.com/manual.html
- RFC 9110 — HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110
- RFC 9112 — HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112
- RFC 9113 — HTTP/2: https://www.rfc-editor.org/rfc/rfc9113
- RFC 9114 — HTTP/3: https://www.rfc-editor.org/rfc/rfc9114
- RFC 9000 — QUIC transport: https://www.rfc-editor.org/rfc/rfc9000
- RFC 8446 — TLS 1.3: https://www.rfc-editor.org/rfc/rfc8446
- RFC 1918 — Private address allocation: https://www.rfc-editor.org/rfc/rfc1918
- RFC 1035 — Domain names (DNS): https://www.rfc-editor.org/rfc/rfc1035
- Julia Evans — networking zines: https://wizardzines.com/
- Book: “Computer Networking: A Top-Down Approach” — Kurose & Ross
- Book: “TCP/IP Illustrated, Vol. 1” — W. Richard Stevens