Split View: 네트워크 & 리눅스 내부 구조 완전 가이드 — TCP/IP, DNS, iptables, systemd
네트워크 & 리눅스 내부 구조 완전 가이드 — TCP/IP, DNS, iptables, systemd
목차
1. OSI 7계층 vs TCP/IP 4계층
네트워크를 이해하려면 먼저 계층 모델을 파악해야 한다. 실무에서는 OSI 7계층보다 TCP/IP 4계층을 더 자주 사용한다.
OSI 7계층 구조
| 계층 | 이름 | 역할 | 프로토콜 예시 |
|---|---|---|---|
| 7 | 응용(Application) | 사용자 인터페이스 | HTTP, FTP, SMTP, DNS |
| 6 | 표현(Presentation) | 데이터 변환, 암호화 | SSL/TLS, JPEG, ASCII |
| 5 | 세션(Session) | 연결 관리 | NetBIOS, RPC |
| 4 | 전송(Transport) | 종단 간 통신 | TCP, UDP |
| 3 | 네트워크(Network) | 라우팅, 주소 지정 | IP, ICMP, ARP |
| 2 | 데이터링크(Data Link) | 프레임 전송 | Ethernet, Wi-Fi |
| 1 | 물리(Physical) | 비트 전송 | 케이블, 허브 |
TCP/IP 4계층 구조
| TCP/IP 계층 | OSI 매핑 | 프로토콜 |
|---|---|---|
| 응용(Application) | 5-7 | HTTP, DNS, SSH, FTP |
| 전송(Transport) | 4 | TCP, UDP |
| 인터넷(Internet) | 3 | IP, ICMP, ARP |
| 네트워크 액세스(Network Access) | 1-2 | Ethernet, Wi-Fi |
캡슐화(Encapsulation) 과정
데이터가 네트워크를 통해 전송될 때 각 계층에서 헤더를 추가한다.
[Application Data]
↓ 응용 계층
[TCP Header | Application Data]
↓ 전송 계층
[IP Header | TCP Header | Application Data]
↓ 인터넷 계층
[Ethernet Header | IP Header | TCP Header | Application Data | Ethernet Trailer]
↓ 네트워크 액세스 계층
실무에서는 tcpdump이나 Wireshark로 각 계층의 헤더를 직접 확인할 수 있다.
# 패킷 캡처 - 각 계층의 헤더를 확인
sudo tcpdump -i eth0 -vvv -c 10
2. TCP 3-way Handshake와 4-way Teardown
TCP는 신뢰성 있는 연결 지향 프로토콜이다. 연결 수립과 해제 과정을 정확히 이해하자.
3-way Handshake (연결 수립)
Client Server
| |
|--- SYN (seq=x) ------->| 1단계: 클라이언트가 SYN 전송
| |
|<-- SYN-ACK (seq=y, | 2단계: 서버가 SYN-ACK 응답
| ack=x+1) ------------|
| |
|--- ACK (ack=y+1) ----->| 3단계: 클라이언트가 ACK 전송
| |
|===== 연결 수립 완료 =====|
4-way Teardown (연결 해제)
Client Server
| |
|--- FIN ---------------->| 1단계: 클라이언트가 FIN 전송
| |
|<-- ACK ----------------| 2단계: 서버가 ACK 응답
| |
|<-- FIN ----------------| 3단계: 서버가 FIN 전송
| |
|--- ACK ----------------->| 4단계: 클라이언트가 ACK 응답
| |
|== TIME_WAIT (2*MSL) ===|
TCP 상태 전이
ss 명령어로 현재 TCP 상태를 확인할 수 있다.
# TCP 연결 상태 확인
ss -tan
# 상태별 연결 수 카운트
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn
주요 TCP 상태:
- LISTEN: 서버가 연결 요청을 대기
- SYN_SENT: 클라이언트가 SYN을 보내고 대기
- ESTABLISHED: 연결이 수립된 상태
- TIME_WAIT: 연결 해제 후 대기 (보통 60초)
- CLOSE_WAIT: 원격에서 FIN을 받고 대기
흐름 제어(Flow Control)
TCP는 슬라이딩 윈도우 방식으로 흐름을 제어한다.
# 현재 TCP 윈도우 크기 확인
ss -ti | grep -A 1 "ESTAB"
# TCP 윈도우 스케일링 설정 확인
sysctl net.ipv4.tcp_window_scaling
혼잡 제어(Congestion Control)
리눅스에서 사용하는 주요 혼잡 제어 알고리즘:
# 현재 혼잡 제어 알고리즘 확인
sysctl net.ipv4.tcp_congestion_control
# 사용 가능한 알고리즘 목록
sysctl net.ipv4.tcp_available_congestion_control
# BBR로 변경 (고대역폭, 고지연 네트워크에 효과적)
sudo sysctl -w net.ipv4.tcp_congestion_control=bbr
주요 알고리즘:
- Cubic: 리눅스 기본 알고리즘, 대부분 환경에서 양호
- BBR: 구글이 개발, 대역폭과 RTT를 기반으로 최적화
- Reno: 고전적 알고리즘, 패킷 손실 기반
3. HTTP/1.1 vs HTTP/2 vs HTTP/3
HTTP/1.1
HTTP/1.1은 텍스트 기반 프로토콜이다.
GET /api/users HTTP/1.1
Host: example.com
Connection: keep-alive
Accept: application/json
주요 특징:
- Keep-Alive: 연결 재사용 가능
- 파이프라이닝: 응답을 기다리지 않고 요청 전송 (실제로는 잘 안 씀)
- Head-of-Line Blocking: 앞 요청이 지연되면 뒤 요청도 대기
HTTP/2
HTTP/2는 바이너리 프레이밍 계층을 도입했다.
단일 TCP 연결 위에서:
Stream 1: GET /index.html ─────> [HEADERS frame] [DATA frame]
Stream 3: GET /style.css ─────> [HEADERS frame] [DATA frame]
Stream 5: GET /script.js ─────> [HEADERS frame] [DATA frame]
주요 개선점:
- 멀티플렉싱: 하나의 TCP 연결로 여러 요청/응답을 동시 처리
- HPACK 헤더 압축: 헤더 크기를 대폭 줄임
- 서버 푸시: 클라이언트가 요청하기 전에 리소스를 선제적으로 전송
- 스트림 우선순위: 중요한 리소스를 먼저 전송
# curl로 HTTP/2 요청
curl -v --http2 https://example.com
# nghttp2로 HTTP/2 프레임 확인
nghttp -v https://example.com
HTTP/3 (QUIC)
HTTP/3는 TCP 대신 QUIC(UDP 기반)를 사용한다.
HTTP/1.1: TCP + TLS (별도 핸드셰이크)
HTTP/2: TCP + TLS (멀티플렉싱, 하지만 TCP의 HOL 블로킹)
HTTP/3: QUIC (UDP 기반, 스트림별 독립적 흐름 제어)
QUIC의 장점:
- 0-RTT 연결: 이전 연결 정보를 재사용하여 즉시 데이터 전송
- 독립적 스트림: 한 스트림의 패킷 손실이 다른 스트림에 영향 없음
- 연결 마이그레이션: IP 주소가 변경되어도 연결 유지 (모바일 환경에 유리)
# curl로 HTTP/3 요청
curl --http3 https://example.com
# QUIC 연결 확인
curl -v --http3 https://cloudflare-quic.com
성능 비교
| 특성 | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| 전송 프로토콜 | TCP | TCP | QUIC (UDP) |
| 멀티플렉싱 | X | O | O |
| 헤더 압축 | X | HPACK | QPACK |
| 서버 푸시 | X | O | O |
| HOL 블로킹 | O | TCP 레벨 | X |
| 0-RTT | X | X | O |
4. DNS 동작 원리
DNS(Domain Name System)는 도메인 이름을 IP 주소로 변환하는 분산 데이터베이스 시스템이다.
DNS 질의 과정
브라우저
|
|-- 1. 로컬 캐시 확인
|
v
로컬 DNS 리졸버 (예: 192.168.1.1)
|
|-- 2. 캐시에 없으면 재귀 질의 시작
|
v
루트 DNS 서버 (.)
|
|-- 3. "com 네임서버는 a.gtld-servers.net입니다"
|
v
TLD DNS 서버 (.com)
|
|-- 4. "example.com 네임서버는 ns1.example.com입니다"
|
v
권한 DNS 서버 (example.com)
|
|-- 5. "example.com의 IP는 93.184.216.34입니다"
|
v
로컬 DNS 리졸버 (캐시에 저장)
|
v
브라우저 (IP 주소로 연결)
재귀 질의 vs 반복 질의
- 재귀 질의(Recursive): 리졸버가 최종 답을 찾을 때까지 대신 질의
- 반복 질의(Iterative): 각 서버가 다음 질의할 서버 주소만 알려줌
DNS 레코드 타입
| 레코드 | 용도 | 예시 |
|---|---|---|
| A | IPv4 주소 매핑 | example.com -> 93.184.216.34 |
| AAAA | IPv6 주소 매핑 | example.com -> 2606:2800:220:1:... |
| CNAME | 도메인 별칭 | www.example.com -> example.com |
| MX | 메일 서버 | example.com -> mail.example.com (priority 10) |
| TXT | 텍스트 정보 | SPF, DKIM, 도메인 소유 증명 |
| NS | 네임서버 지정 | example.com -> ns1.example.com |
| SOA | 존 정보 | 시리얼 번호, 갱신 주기 |
| SRV | 서비스 위치 | 특정 서비스의 호스트와 포트 |
| PTR | 역방향 DNS | IP -> 도메인 이름 |
dig 명령어 활용
# A 레코드 조회
dig example.com A
# 특정 DNS 서버로 조회
dig @8.8.8.8 example.com
# MX 레코드 조회
dig example.com MX
# TXT 레코드 조회 (SPF 확인)
dig example.com TXT
# 역방향 DNS 조회
dig -x 93.184.216.34
# 전체 DNS 추적 (+trace)
dig +trace example.com
# 짧은 출력
dig +short example.com
# DNSSEC 검증
dig +dnssec example.com
DNS 캐시 관리
# 리눅스 systemd-resolved 캐시 확인
resolvectl statistics
# DNS 캐시 플러시
sudo resolvectl flush-caches
# /etc/resolv.conf 확인
cat /etc/resolv.conf
# nsswitch.conf에서 DNS 해석 순서 확인
grep hosts /etc/nsswitch.conf
5. TLS/SSL 핸드셰이크
HTTPS는 HTTP에 TLS(Transport Layer Security)를 결합한 것이다.
TLS 1.3 핸드셰이크 과정
Client Server
| |
|--- ClientHello ------------------> | 지원하는 암호화 스위트, 키 공유
| (+ key_share) |
| |
|<-- ServerHello ------------------- | 선택된 암호화 스위트, 키 공유
| (+ key_share) |
|<-- EncryptedExtensions ----------- |
|<-- Certificate ------------------- | 서버 인증서
|<-- CertificateVerify ------------- | 서명 검증
|<-- Finished ---------------------- |
| |
|--- Finished ---------------------> |
| |
|==== 암호화된 통신 시작 ===========|
TLS 1.3의 주요 개선점:
- 1-RTT 핸드셰이크: TLS 1.2의 2-RTT에서 1-RTT로 단축
- 0-RTT 재개: 이전 연결의 PSK를 사용하여 즉시 데이터 전송
- 안전하지 않은 알고리즘 제거: RC4, DES, MD5 등 제거
- Perfect Forward Secrecy 필수: ECDHE만 허용
인증서 체인
Root CA (자체 서명)
|
|-- Intermediate CA (Root CA가 서명)
|
|-- 서버 인증서 (Intermediate CA가 서명)
# 인증서 체인 확인
openssl s_client -connect example.com:443 -showcerts
# 인증서 상세 정보
openssl x509 -in cert.pem -text -noout
# 인증서 만료일 확인
echo | openssl s_client -connect example.com:443 2>/dev/null | \
openssl x509 -noout -dates
# TLS 버전 및 암호화 스위트 확인
openssl s_client -connect example.com:443 -tls1_3
Let's Encrypt로 인증서 발급
# certbot 설치 (Ubuntu)
sudo apt install certbot python3-certbot-nginx
# 인증서 발급 (Nginx)
sudo certbot --nginx -d example.com -d www.example.com
# 인증서 갱신 테스트
sudo certbot renew --dry-run
# 자동 갱신 타이머 확인
systemctl list-timers | grep certbot
6. 리눅스 네트워크 스택
소켓(Socket) 기초
소켓은 네트워크 통신의 종단점이다. 리눅스에서 소켓은 파일 디스크립터로 관리된다.
# 열린 소켓 확인
ss -tuln
# 프로세스별 소켓 확인
ss -tulnp
# 소켓 통계
ss -s
epoll - 고성능 I/O 멀티플렉싱
리눅스의 epoll은 대량의 파일 디스크립터를 효율적으로 모니터링한다.
select/poll: O(n) - 모든 fd를 순회하여 확인
epoll: O(1) - 이벤트가 발생한 fd만 반환
epoll의 동작:
1. epoll_create() - epoll 인스턴스 생성
2. epoll_ctl() - 모니터링할 fd 등록/수정/삭제
3. epoll_wait() - 이벤트 대기 (블로킹 또는 논블로킹)
Nginx, Redis, Node.js 등 고성능 서버는 모두 epoll을 기반으로 동작한다.
iptables / nftables
iptables는 리눅스 커널의 netfilter 프레임워크를 사용하는 패킷 필터링 도구다.
iptables 체인 구조
PREROUTING
|
[라우팅 결정]
/ \
INPUT FORWARD
| |
[로컬 프로세스] [다른 인터페이스]
| |
OUTPUT POSTROUTING
\ /
POSTROUTING
iptables 기본 명령어
# 현재 규칙 확인
sudo iptables -L -n -v
# 특정 포트 허용
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 특정 IP 차단
sudo iptables -A INPUT -s 10.0.0.100 -j DROP
# SSH 접속 제한 (분당 3회)
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --set --name SSH
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
# NAT 설정 (마스커레이드)
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# 규칙 저장
sudo iptables-save > /etc/iptables/rules.v4
nftables (iptables 후속)
# nft로 현재 규칙 확인
sudo nft list ruleset
# 테이블 생성
sudo nft add table inet my_filter
# 체인 생성
sudo nft add chain inet my_filter input \
'{ type filter hook input priority 0; policy drop; }'
# 규칙 추가
sudo nft add rule inet my_filter input tcp dport 80 accept
sudo nft add rule inet my_filter input tcp dport 443 accept
# 규칙 저장
sudo nft list ruleset > /etc/nftables.conf
라우팅 테이블
# 라우팅 테이블 확인
ip route show
# 기본 게이트웨이 확인
ip route | grep default
# 특정 목적지에 대한 경로 확인
ip route get 8.8.8.8
# 정적 라우트 추가
sudo ip route add 10.10.0.0/24 via 192.168.1.1 dev eth0
# 라우팅 테이블에 정책 기반 라우팅
sudo ip rule add from 10.0.1.0/24 table 100
sudo ip route add default via 10.0.1.1 table 100
7. systemd 완벽 가이드
유닛 파일 구조
systemd는 유닛 파일로 서비스, 타이머, 마운트 등을 관리한다.
유닛 파일 위치:
/etc/systemd/system/- 관리자가 생성한 유닛 (최우선)/run/systemd/system/- 런타임 유닛/usr/lib/systemd/system/- 패키지가 설치한 유닛
서비스 유닛 파일 예시
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application Server
After=network.target postgresql.service
Requires=postgresql.service
Documentation=https://example.com/docs
[Service]
Type=notify
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
Environment=NODE_ENV=production
EnvironmentFile=/etc/myapp/env
ExecStartPre=/opt/myapp/scripts/check-deps.sh
ExecStart=/usr/bin/node /opt/myapp/server.js
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StartLimitBurst=3
StartLimitIntervalSec=60
# 보안 강화
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp /var/log/myapp
PrivateTmp=true
[Install]
WantedBy=multi-user.target
서비스 관리 명령어
# 서비스 상태 확인
systemctl status myapp.service
# 서비스 시작/중지/재시작
sudo systemctl start myapp.service
sudo systemctl stop myapp.service
sudo systemctl restart myapp.service
# 설정 변경 후 재로드 (PID 유지)
sudo systemctl reload myapp.service
# 부팅 시 자동 시작 설정
sudo systemctl enable myapp.service
sudo systemctl enable --now myapp.service # 즉시 시작 + 자동 시작
# 유닛 파일 수정 후 데몬 리로드
sudo systemctl daemon-reload
# 실패한 서비스 확인
systemctl --failed
# 서비스 의존성 확인
systemctl list-dependencies myapp.service
journalctl - 로그 관리
# 특정 서비스 로그 확인
journalctl -u myapp.service
# 실시간 로그 모니터링
journalctl -u myapp.service -f
# 최근 1시간 로그
journalctl -u myapp.service --since "1 hour ago"
# 특정 시간 범위
journalctl --since "2026-04-12 10:00:00" --until "2026-04-12 12:00:00"
# 에러 레벨 이상만 표시
journalctl -u myapp.service -p err
# 부팅별 로그
journalctl -b -1 # 이전 부팅
journalctl -b 0 # 현재 부팅
# 디스크 사용량 확인
journalctl --disk-usage
# 오래된 로그 삭제
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=500M
systemd 타이머 (cron 대체)
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Daily Backup
[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh
# 타이머 활성화
sudo systemctl enable --now backup.timer
# 모든 타이머 확인
systemctl list-timers --all
# 타이머 다음 실행 시간 확인
systemctl status backup.timer
8. 프로세스 관리
fork/exec 모델
리눅스에서 새 프로세스는 fork()로 현재 프로세스를 복제한 후, exec()로 새 프로그램을 실행한다.
Parent Process (PID 100)
|
|-- fork() --> Child Process (PID 101)
|
|-- exec("/bin/ls") --> ls 프로그램 실행
# 프로세스 트리 확인
pstree -p
# 특정 프로세스의 상세 정보
cat /proc/PID/status
# 프로세스가 사용하는 파일 디스크립터
ls -la /proc/PID/fd/
좀비 프로세스와 고아 프로세스
# 좀비 프로세스 확인
ps aux | awk '$8 ~ /Z/'
# 고아 프로세스는 init(PID 1)이 자동으로 입양
# 좀비 프로세스는 부모가 wait()를 호출해야 제거됨
# 좀비 프로세스의 부모 찾기
ps -eo pid,ppid,stat,cmd | grep -w Z
좀비 프로세스 해결 방법:
- 부모 프로세스에 SIGCHLD 시그널 전송
- 부모 프로세스 종료 (init이 좀비를 정리)
- 애플리케이션 코드에서
wait()또는waitpid()호출
cgroups (Control Groups)
cgroups는 프로세스 그룹의 리소스 사용량을 제한한다.
# cgroup v2 확인
mount | grep cgroup2
# 현재 cgroup 확인
cat /proc/self/cgroup
# CPU 사용량 제한 예시
# 50%로 CPU 제한하는 cgroup 생성
sudo mkdir /sys/fs/cgroup/my_limited_group
echo "50000 100000" | sudo tee /sys/fs/cgroup/my_limited_group/cpu.max
# 메모리 제한 (512MB)
echo "536870912" | sudo tee /sys/fs/cgroup/my_limited_group/memory.max
# 프로세스를 cgroup에 할당
echo PID | sudo tee /sys/fs/cgroup/my_limited_group/cgroup.procs
namespaces (네임스페이스)
네임스페이스는 프로세스를 격리된 환경에서 실행한다. Docker 컨테이너의 핵심 기술이다.
| 네임스페이스 | 격리 대상 | 플래그 |
|---|---|---|
| PID | 프로세스 ID | CLONE_NEWPID |
| Network | 네트워크 스택 | CLONE_NEWNET |
| Mount | 파일시스템 마운트 | CLONE_NEWNS |
| UTS | 호스트네임 | CLONE_NEWUTS |
| IPC | IPC 리소스 | CLONE_NEWIPC |
| User | 사용자/그룹 ID | CLONE_NEWUSER |
| Cgroup | cgroup 루트 | CLONE_NEWCGROUP |
# 네임스페이스 확인
lsns
# 새 네트워크 네임스페이스 생성
sudo ip netns add test_ns
# 네임스페이스 내에서 명령 실행
sudo ip netns exec test_ns ip addr
# unshare로 격리된 환경 생성
sudo unshare --pid --fork --mount-proc bash
# 네임스페이스 목록
ip netns list
9. 리눅스 파일 시스템
VFS (Virtual File System)
VFS는 다양한 파일 시스템을 동일한 인터페이스로 접근하게 해주는 추상화 계층이다.
사용자 프로세스
|
|-- open(), read(), write() ...
|
v
VFS (Virtual File System)
|
├── ext4
├── XFS
├── btrfs
├── NFS
├── procfs (/proc)
└── sysfs (/sys)
inode (아이노드)
모든 파일은 inode로 메타데이터를 관리한다.
# 파일의 inode 번호 확인
ls -i file.txt
# inode 상세 정보
stat file.txt
# 파일 시스템의 inode 사용량 확인
df -i
# 하드링크 vs 심볼릭링크
# 하드링크: 같은 inode를 공유
ln original.txt hardlink.txt
# 심볼릭링크: 별도 inode, 경로를 가리킴
ln -s original.txt symlink.txt
파일 시스템 비교
| 특성 | ext4 | XFS | btrfs |
|---|---|---|---|
| 최대 파일 크기 | 16TB | 8EB | 16EB |
| 최대 볼륨 크기 | 1EB | 8EB | 16EB |
| 스냅샷 | X | X | O (CoW) |
| 압축 | X | X | O |
| RAID 지원 | 외부 | 외부 | 내장 |
| 온라인 리사이즈 | 확장만 | 확장만 | 확장+축소 |
| 적합 용도 | 범용 | 대용량 파일 | 스냅샷/백업 |
# 파일 시스템 타입 확인
df -Th
# 파일 시스템 상세 정보
sudo tune2fs -l /dev/sda1 # ext4
sudo xfs_info /dev/sda1 # XFS
sudo btrfs filesystem show # btrfs
/proc 파일 시스템
/proc는 커널과 프로세스 정보를 파일로 노출하는 가상 파일 시스템이다.
# CPU 정보
cat /proc/cpuinfo
# 메모리 정보
cat /proc/meminfo
# 로드 평균
cat /proc/loadavg
# 커널 버전
cat /proc/version
# 네트워크 연결 정보
cat /proc/net/tcp
# 특정 프로세스 정보
cat /proc/PID/status # 프로세스 상태
cat /proc/PID/maps # 메모리 맵
cat /proc/PID/cmdline # 실행 명령
/sys 파일 시스템
/sys는 커널의 장치 모델 정보를 노출한다.
# 블록 장치 정보
ls /sys/block/
# 네트워크 인터페이스 정보
ls /sys/class/net/
# CPU 주파수 정보
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
# 디스크 스케줄러 확인
cat /sys/block/sda/queue/scheduler
10. 트러블슈팅 도구 모음
ss (Socket Statistics)
ss는 netstat의 현대적 대체 도구다.
# 모든 TCP 연결 (수신 대기 포함)
ss -tuln
# ESTABLISHED 상태인 연결만
ss -t state established
# 특정 포트로의 연결 수 확인
ss -tn dport = :443 | wc -l
# 프로세스 정보 포함
ss -tulnp
# 소켓 메모리 사용량
ss -tm
# TIME_WAIT 상태 연결 확인
ss -t state time-wait
tcpdump
# 특정 인터페이스에서 패킷 캡처
sudo tcpdump -i eth0
# 특정 호스트와의 통신만 캡처
sudo tcpdump -i eth0 host 10.0.0.1
# 특정 포트 캡처
sudo tcpdump -i eth0 port 80
# DNS 쿼리 캡처
sudo tcpdump -i eth0 port 53
# 패킷을 파일로 저장
sudo tcpdump -i eth0 -w capture.pcap
# 저장된 파일 읽기
tcpdump -r capture.pcap
# HTTP 요청/응답 내용 보기
sudo tcpdump -i eth0 -A port 80
# SYN 패킷만 캡처 (새 연결 모니터링)
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'
strace
# 시스템 콜 추적
strace -p PID
# 특정 시스템 콜만 추적
strace -e trace=network -p PID
# 파일 관련 시스템 콜
strace -e trace=file ls
# 시간 정보 포함
strace -T -p PID
# 자식 프로세스도 추적
strace -f -p PID
# 출력을 파일로 저장
strace -o output.txt -p PID
lsof (List Open Files)
# 특정 포트를 사용하는 프로세스 확인
sudo lsof -i :80
# 특정 프로세스가 열고 있는 파일
lsof -p PID
# 특정 파일을 사용하는 프로세스
lsof /var/log/syslog
# 삭제되었지만 열려있는 파일 (디스크 공간 회수 안 됨)
lsof +L1
# 네트워크 연결 확인
lsof -i -P -n
# 특정 사용자의 열린 파일
lsof -u username
perf (Performance Counters)
# CPU 프로파일링 (10초)
sudo perf record -g -p PID -- sleep 10
# 결과 확인
sudo perf report
# 실시간 상위 함수 확인
sudo perf top -p PID
# 시스템 전체 통계
sudo perf stat -a -- sleep 5
# 플레임 그래프 생성
sudo perf record -g -p PID -- sleep 30
sudo perf script > out.perf
# FlameGraph 도구로 변환
./stackcollapse-perf.pl out.perf > out.folded
./flamegraph.pl out.folded > flamegraph.svg
종합 트러블슈팅 체크리스트
네트워크 문제가 발생했을 때 순서대로 확인하는 체크리스트:
# 1. 인터페이스 상태 확인
ip addr show
ip link show
# 2. 라우팅 확인
ip route show
traceroute TARGET_HOST
# 3. DNS 확인
dig TARGET_DOMAIN
nslookup TARGET_DOMAIN
# 4. 연결 확인
ping TARGET_HOST
curl -v http://TARGET_HOST
# 5. 포트 확인
ss -tuln
sudo lsof -i :PORT
# 6. 방화벽 확인
sudo iptables -L -n
sudo nft list ruleset
# 7. 패킷 캡처
sudo tcpdump -i eth0 host TARGET_HOST
# 8. 시스템 리소스 확인
top
free -h
df -h
# 9. 로그 확인
journalctl -xe
dmesg | tail
마무리
이 글에서 다룬 내용을 요약하면:
- 네트워크 기초: OSI/TCP/IP 계층 모델, TCP 핸드셰이크, 흐름/혼잡 제어
- 웹 프로토콜: HTTP/1.1에서 HTTP/3까지의 발전, TLS 핸드셰이크
- DNS: 질의 과정, 레코드 타입, dig 활용
- 리눅스 네트워크: 소켓, epoll, iptables/nftables, 라우팅
- systemd: 유닛 파일, 서비스 관리, journalctl, 타이머
- 프로세스: fork/exec, 좀비/고아, cgroups, namespaces
- 파일 시스템: VFS, inode, ext4/XFS/btrfs, /proc, /sys
- 트러블슈팅: ss, tcpdump, strace, lsof, perf
이 지식은 서버 운영, 인프라 관리, DevOps 업무에서 매일 사용된다. 문제가 발생했을 때 어떤 계층에서 문제가 생겼는지 빠르게 파악하는 것이 핵심이다. 각 도구를 실제 환경에서 직접 실행해보면서 익히는 것을 권장한다.
The Complete Guide to Networking & Linux Internals — TCP/IP, DNS, iptables, systemd
Table of Contents
1. OSI 7 Layers vs TCP/IP 4 Layers
To understand networking, you first need to grasp layered models. In practice, the TCP/IP 4-layer model is used more often than the OSI 7-layer model.
OSI 7-Layer Structure
| Layer | Name | Role | Protocol Examples |
|---|---|---|---|
| 7 | Application | User interface | HTTP, FTP, SMTP, DNS |
| 6 | Presentation | Data transformation, encryption | SSL/TLS, JPEG, ASCII |
| 5 | Session | Connection management | NetBIOS, RPC |
| 4 | Transport | End-to-end communication | TCP, UDP |
| 3 | Network | Routing, addressing | IP, ICMP, ARP |
| 2 | Data Link | Frame transmission | Ethernet, Wi-Fi |
| 1 | Physical | Bit transmission | Cables, hubs |
TCP/IP 4-Layer Structure
| TCP/IP Layer | OSI Mapping | Protocols |
|---|---|---|
| Application | 5-7 | HTTP, DNS, SSH, FTP |
| Transport | 4 | TCP, UDP |
| Internet | 3 | IP, ICMP, ARP |
| Network Access | 1-2 | Ethernet, Wi-Fi |
Encapsulation Process
When data travels across the network, each layer adds its own header.
[Application Data]
↓ Application Layer
[TCP Header | Application Data]
↓ Transport Layer
[IP Header | TCP Header | Application Data]
↓ Internet Layer
[Ethernet Header | IP Header | TCP Header | Application Data | Ethernet Trailer]
↓ Network Access Layer
In practice, you can inspect each layer's headers using tcpdump or Wireshark.
# Capture packets and inspect layer headers
sudo tcpdump -i eth0 -vvv -c 10
2. TCP 3-Way Handshake and 4-Way Teardown
TCP is a reliable, connection-oriented protocol. Let us understand the connection establishment and termination processes precisely.
3-Way Handshake (Connection Establishment)
Client Server
| |
|--- SYN (seq=x) ------->| Step 1: Client sends SYN
| |
|<-- SYN-ACK (seq=y, | Step 2: Server responds with SYN-ACK
| ack=x+1) ------------|
| |
|--- ACK (ack=y+1) ----->| Step 3: Client sends ACK
| |
|=== Connection Ready ====|
4-Way Teardown (Connection Termination)
Client Server
| |
|--- FIN ----------------->| Step 1: Client sends FIN
| |
|<-- ACK -----------------| Step 2: Server sends ACK
| |
|<-- FIN -----------------| Step 3: Server sends FIN
| |
|--- ACK ----------------->| Step 4: Client sends ACK
| |
|== TIME_WAIT (2*MSL) ====|
TCP State Transitions
You can check the current TCP states using the ss command.
# Check TCP connection states
ss -tan
# Count connections by state
ss -tan | awk 'NR>1 {print $1}' | sort | uniq -c | sort -rn
Key TCP states:
- LISTEN: Server waiting for connection requests
- SYN_SENT: Client has sent SYN, waiting for response
- ESTABLISHED: Connection is active
- TIME_WAIT: Waiting after connection termination (typically 60 seconds)
- CLOSE_WAIT: Received FIN from remote, waiting to close
Flow Control
TCP uses a sliding window mechanism for flow control.
# Check current TCP window sizes
ss -ti | grep -A 1 "ESTAB"
# Check TCP window scaling settings
sysctl net.ipv4.tcp_window_scaling
Congestion Control
Key congestion control algorithms used in Linux:
# Check current congestion control algorithm
sysctl net.ipv4.tcp_congestion_control
# List available algorithms
sysctl net.ipv4.tcp_available_congestion_control
# Switch to BBR (effective for high-bandwidth, high-latency networks)
sudo sysctl -w net.ipv4.tcp_congestion_control=bbr
Key algorithms:
- Cubic: Linux default, performs well in most environments
- BBR: Developed by Google, optimizes based on bandwidth and RTT
- Reno: Classic algorithm, loss-based detection
3. HTTP/1.1 vs HTTP/2 vs HTTP/3
HTTP/1.1
HTTP/1.1 is a text-based protocol.
GET /api/users HTTP/1.1
Host: example.com
Connection: keep-alive
Accept: application/json
Key characteristics:
- Keep-Alive: Allows connection reuse
- Pipelining: Sends requests without waiting for responses (rarely used in practice)
- Head-of-Line Blocking: If the first request stalls, all subsequent requests wait
HTTP/2
HTTP/2 introduced the binary framing layer.
On a single TCP connection:
Stream 1: GET /index.html ─────> [HEADERS frame] [DATA frame]
Stream 3: GET /style.css ─────> [HEADERS frame] [DATA frame]
Stream 5: GET /script.js ─────> [HEADERS frame] [DATA frame]
Key improvements:
- Multiplexing: Multiple requests/responses over a single TCP connection
- HPACK header compression: Dramatically reduces header sizes
- Server push: Proactively sends resources before the client requests them
- Stream prioritization: Delivers critical resources first
# HTTP/2 request with curl
curl -v --http2 https://example.com
# Inspect HTTP/2 frames with nghttp2
nghttp -v https://example.com
HTTP/3 (QUIC)
HTTP/3 uses QUIC (UDP-based) instead of TCP.
HTTP/1.1: TCP + TLS (separate handshakes)
HTTP/2: TCP + TLS (multiplexing, but TCP-level HOL blocking)
HTTP/3: QUIC (UDP-based, independent flow control per stream)
QUIC advantages:
- 0-RTT connection: Reuses previous connection info for immediate data transfer
- Independent streams: Packet loss in one stream does not affect others
- Connection migration: Maintains connection even when IP changes (great for mobile)
# HTTP/3 request with curl
curl --http3 https://example.com
# Verify QUIC connection
curl -v --http3 https://cloudflare-quic.com
Performance Comparison
| Feature | HTTP/1.1 | HTTP/2 | HTTP/3 |
|---|---|---|---|
| Transport | TCP | TCP | QUIC (UDP) |
| Multiplexing | No | Yes | Yes |
| Header Compression | No | HPACK | QPACK |
| Server Push | No | Yes | Yes |
| HOL Blocking | Yes | At TCP level | No |
| 0-RTT | No | No | Yes |
4. How DNS Works
DNS (Domain Name System) is a distributed database system that translates domain names into IP addresses.
DNS Query Process
Browser
|
|-- 1. Check local cache
|
v
Local DNS Resolver (e.g., 192.168.1.1)
|
|-- 2. If not cached, start recursive query
|
v
Root DNS Server (.)
|
|-- 3. "The nameserver for .com is a.gtld-servers.net"
|
v
TLD DNS Server (.com)
|
|-- 4. "The nameserver for example.com is ns1.example.com"
|
v
Authoritative DNS Server (example.com)
|
|-- 5. "The IP for example.com is 93.184.216.34"
|
v
Local DNS Resolver (caches the result)
|
v
Browser (connects to IP address)
Recursive vs Iterative Queries
- Recursive query: The resolver handles the entire lookup on behalf of the client
- Iterative query: Each server returns the address of the next server to query
DNS Record Types
| Record | Purpose | Example |
|---|---|---|
| A | IPv4 address mapping | example.com -> 93.184.216.34 |
| AAAA | IPv6 address mapping | example.com -> 2606:2800:220:1:... |
| CNAME | Domain alias | www.example.com -> example.com |
| MX | Mail server | example.com -> mail.example.com (priority 10) |
| TXT | Text information | SPF, DKIM, domain ownership verification |
| NS | Nameserver delegation | example.com -> ns1.example.com |
| SOA | Zone info | Serial number, refresh intervals |
| SRV | Service location | Host and port for a specific service |
| PTR | Reverse DNS | IP -> domain name |
Using the dig Command
# Query A record
dig example.com A
# Query with a specific DNS server
dig @8.8.8.8 example.com
# Query MX record
dig example.com MX
# Query TXT record (check SPF)
dig example.com TXT
# Reverse DNS lookup
dig -x 93.184.216.34
# Full DNS trace
dig +trace example.com
# Short output
dig +short example.com
# DNSSEC validation
dig +dnssec example.com
DNS Cache Management
# Check systemd-resolved cache statistics (Linux)
resolvectl statistics
# Flush DNS cache
sudo resolvectl flush-caches
# Inspect /etc/resolv.conf
cat /etc/resolv.conf
# Check DNS resolution order in nsswitch.conf
grep hosts /etc/nsswitch.conf
5. TLS/SSL Handshake
HTTPS combines HTTP with TLS (Transport Layer Security).
TLS 1.3 Handshake Process
Client Server
| |
|--- ClientHello ------------------> | Supported cipher suites, key share
| (+ key_share) |
| |
|<-- ServerHello ------------------- | Selected cipher suite, key share
| (+ key_share) |
|<-- EncryptedExtensions ----------- |
|<-- Certificate ------------------- | Server certificate
|<-- CertificateVerify ------------- | Signature verification
|<-- Finished ---------------------- |
| |
|--- Finished ---------------------> |
| |
|==== Encrypted Communication ======|
Key improvements in TLS 1.3:
- 1-RTT handshake: Reduced from 2-RTT in TLS 1.2 to 1-RTT
- 0-RTT resumption: Uses PSK from previous connections for immediate data transfer
- Removed insecure algorithms: RC4, DES, MD5, etc.
- Mandatory Perfect Forward Secrecy: Only ECDHE allowed
Certificate Chain
Root CA (self-signed)
|
|-- Intermediate CA (signed by Root CA)
|
|-- Server Certificate (signed by Intermediate CA)
# Inspect certificate chain
openssl s_client -connect example.com:443 -showcerts
# View certificate details
openssl x509 -in cert.pem -text -noout
# Check certificate expiration
echo | openssl s_client -connect example.com:443 2>/dev/null | \
openssl x509 -noout -dates
# Verify TLS version and cipher suite
openssl s_client -connect example.com:443 -tls1_3
Issuing Certificates with Let's Encrypt
# Install certbot (Ubuntu)
sudo apt install certbot python3-certbot-nginx
# Issue certificate (Nginx)
sudo certbot --nginx -d example.com -d www.example.com
# Test certificate renewal
sudo certbot renew --dry-run
# Check auto-renewal timer
systemctl list-timers | grep certbot
6. Linux Network Stack
Socket Basics
A socket is an endpoint for network communication. In Linux, sockets are managed as file descriptors.
# List open sockets
ss -tuln
# Show sockets with process info
ss -tulnp
# Socket statistics
ss -s
epoll - High-Performance I/O Multiplexing
Linux's epoll efficiently monitors large numbers of file descriptors.
select/poll: O(n) - scans all fds to find ready ones
epoll: O(1) - returns only the fds with events
How epoll works:
1. epoll_create() - create epoll instance
2. epoll_ctl() - register/modify/delete fds to monitor
3. epoll_wait() - wait for events (blocking or non-blocking)
Nginx, Redis, Node.js, and other high-performance servers all rely on epoll.
iptables / nftables
iptables is a packet filtering tool that uses the Linux kernel's netfilter framework.
iptables Chain Structure
PREROUTING
|
[Routing Decision]
/ \
INPUT FORWARD
| |
[Local Process] [Other Interface]
| |
OUTPUT POSTROUTING
\ /
POSTROUTING
Basic iptables Commands
# List current rules
sudo iptables -L -n -v
# Allow specific ports
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Block a specific IP
sudo iptables -A INPUT -s 10.0.0.100 -j DROP
# Rate-limit SSH (3 per minute)
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --set --name SSH
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW \
-m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
# NAT configuration (masquerade)
sudo iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
# Save rules
sudo iptables-save > /etc/iptables/rules.v4
nftables (iptables Successor)
# List current nft rules
sudo nft list ruleset
# Create a table
sudo nft add table inet my_filter
# Create a chain
sudo nft add chain inet my_filter input \
'{ type filter hook input priority 0; policy drop; }'
# Add rules
sudo nft add rule inet my_filter input tcp dport 80 accept
sudo nft add rule inet my_filter input tcp dport 443 accept
# Save rules
sudo nft list ruleset > /etc/nftables.conf
Routing Table
# Show routing table
ip route show
# Check default gateway
ip route | grep default
# Find route to a specific destination
ip route get 8.8.8.8
# Add a static route
sudo ip route add 10.10.0.0/24 via 192.168.1.1 dev eth0
# Policy-based routing
sudo ip rule add from 10.0.1.0/24 table 100
sudo ip route add default via 10.0.1.1 table 100
7. systemd Complete Guide
Unit File Structure
systemd manages services, timers, mounts, and more through unit files.
Unit file locations:
/etc/systemd/system/- Admin-created units (highest priority)/run/systemd/system/- Runtime units/usr/lib/systemd/system/- Package-installed units
Example Service Unit File
# /etc/systemd/system/myapp.service
[Unit]
Description=My Application Server
After=network.target postgresql.service
Requires=postgresql.service
Documentation=https://example.com/docs
[Service]
Type=notify
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
Environment=NODE_ENV=production
EnvironmentFile=/etc/myapp/env
ExecStartPre=/opt/myapp/scripts/check-deps.sh
ExecStart=/usr/bin/node /opt/myapp/server.js
ExecReload=/bin/kill -HUP $MAINPID
Restart=on-failure
RestartSec=5
StartLimitBurst=3
StartLimitIntervalSec=60
# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
ReadWritePaths=/var/lib/myapp /var/log/myapp
PrivateTmp=true
[Install]
WantedBy=multi-user.target
Service Management Commands
# Check service status
systemctl status myapp.service
# Start/stop/restart service
sudo systemctl start myapp.service
sudo systemctl stop myapp.service
sudo systemctl restart myapp.service
# Reload configuration without restarting (PID preserved)
sudo systemctl reload myapp.service
# Enable auto-start at boot
sudo systemctl enable myapp.service
sudo systemctl enable --now myapp.service # Start immediately + auto-start
# Reload daemon after unit file changes
sudo systemctl daemon-reload
# List failed services
systemctl --failed
# Show service dependencies
systemctl list-dependencies myapp.service
journalctl - Log Management
# View logs for a specific service
journalctl -u myapp.service
# Follow logs in real-time
journalctl -u myapp.service -f
# Logs from the last hour
journalctl -u myapp.service --since "1 hour ago"
# Specific time range
journalctl --since "2026-04-12 10:00:00" --until "2026-04-12 12:00:00"
# Show only error level and above
journalctl -u myapp.service -p err
# Logs by boot
journalctl -b -1 # Previous boot
journalctl -b 0 # Current boot
# Check disk usage
journalctl --disk-usage
# Clean up old logs
sudo journalctl --vacuum-time=7d
sudo journalctl --vacuum-size=500M
systemd Timers (cron Replacement)
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily Backup Timer
[Timer]
OnCalendar=*-*-* 02:00:00
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
# /etc/systemd/system/backup.service
[Unit]
Description=Daily Backup
[Service]
Type=oneshot
ExecStart=/opt/scripts/backup.sh
# Enable timer
sudo systemctl enable --now backup.timer
# List all timers
systemctl list-timers --all
# Check next timer execution
systemctl status backup.timer
8. Process Management
The fork/exec Model
In Linux, new processes are created by fork() which duplicates the current process, followed by exec() which replaces it with a new program.
Parent Process (PID 100)
|
|-- fork() --> Child Process (PID 101)
|
|-- exec("/bin/ls") --> ls program executes
# View process tree
pstree -p
# Detailed info for a specific process
cat /proc/PID/status
# File descriptors used by a process
ls -la /proc/PID/fd/
Zombie and Orphan Processes
# Find zombie processes
ps aux | awk '$8 ~ /Z/'
# Orphan processes are automatically adopted by init (PID 1)
# Zombie processes require the parent to call wait() for cleanup
# Find the parent of zombie processes
ps -eo pid,ppid,stat,cmd | grep -w Z
Resolving zombie processes:
- Send SIGCHLD signal to the parent process
- Terminate the parent process (init will reap the zombie)
- Call
wait()orwaitpid()in the application code
cgroups (Control Groups)
cgroups limit resource usage for groups of processes.
# Verify cgroup v2
mount | grep cgroup2
# Check current cgroup
cat /proc/self/cgroup
# Create a CPU-limited cgroup (50%)
sudo mkdir /sys/fs/cgroup/my_limited_group
echo "50000 100000" | sudo tee /sys/fs/cgroup/my_limited_group/cpu.max
# Memory limit (512MB)
echo "536870912" | sudo tee /sys/fs/cgroup/my_limited_group/memory.max
# Assign a process to the cgroup
echo PID | sudo tee /sys/fs/cgroup/my_limited_group/cgroup.procs
Namespaces
Namespaces run processes in isolated environments. They are the core technology behind Docker containers.
| Namespace | Isolates | Flag |
|---|---|---|
| PID | Process IDs | CLONE_NEWPID |
| Network | Network stack | CLONE_NEWNET |
| Mount | Filesystem mounts | CLONE_NEWNS |
| UTS | Hostname | CLONE_NEWUTS |
| IPC | IPC resources | CLONE_NEWIPC |
| User | User/group IDs | CLONE_NEWUSER |
| Cgroup | Cgroup root | CLONE_NEWCGROUP |
# List namespaces
lsns
# Create a new network namespace
sudo ip netns add test_ns
# Run command inside namespace
sudo ip netns exec test_ns ip addr
# Create an isolated environment with unshare
sudo unshare --pid --fork --mount-proc bash
# List namespaces
ip netns list
9. Linux File System
VFS (Virtual File System)
VFS is an abstraction layer that provides a uniform interface to access various file systems.
User Process
|
|-- open(), read(), write() ...
|
v
VFS (Virtual File System)
|
├── ext4
├── XFS
├── btrfs
├── NFS
├── procfs (/proc)
└── sysfs (/sys)
inode
Every file has an inode that stores its metadata.
# Check file inode number
ls -i file.txt
# Detailed inode information
stat file.txt
# Check filesystem inode usage
df -i
# Hard link vs symbolic link
# Hard link: shares the same inode
ln original.txt hardlink.txt
# Symbolic link: separate inode, points to a path
ln -s original.txt symlink.txt
File System Comparison
| Feature | ext4 | XFS | btrfs |
|---|---|---|---|
| Max file size | 16TB | 8EB | 16EB |
| Max volume size | 1EB | 8EB | 16EB |
| Snapshots | No | No | Yes (CoW) |
| Compression | No | No | Yes |
| RAID support | External | External | Built-in |
| Online resize | Grow only | Grow only | Grow + shrink |
| Best for | General purpose | Large files | Snapshots/backups |
# Check filesystem types
df -Th
# Filesystem details
sudo tune2fs -l /dev/sda1 # ext4
sudo xfs_info /dev/sda1 # XFS
sudo btrfs filesystem show # btrfs
/proc Filesystem
/proc is a virtual filesystem that exposes kernel and process information as files.
# CPU information
cat /proc/cpuinfo
# Memory information
cat /proc/meminfo
# Load average
cat /proc/loadavg
# Kernel version
cat /proc/version
# Network connection info
cat /proc/net/tcp
# Specific process information
cat /proc/PID/status # Process status
cat /proc/PID/maps # Memory map
cat /proc/PID/cmdline # Command line
/sys Filesystem
/sys exposes the kernel's device model information.
# Block device info
ls /sys/block/
# Network interface info
ls /sys/class/net/
# CPU frequency info
cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
# Disk scheduler
cat /sys/block/sda/queue/scheduler
10. Troubleshooting Toolkit
ss (Socket Statistics)
ss is the modern replacement for netstat.
# All TCP connections (including listening)
ss -tuln
# Only ESTABLISHED connections
ss -t state established
# Count connections to a specific port
ss -tn dport = :443 | wc -l
# Include process information
ss -tulnp
# Socket memory usage
ss -tm
# TIME_WAIT connections
ss -t state time-wait
tcpdump
# Capture on a specific interface
sudo tcpdump -i eth0
# Capture traffic to/from a specific host
sudo tcpdump -i eth0 host 10.0.0.1
# Capture on a specific port
sudo tcpdump -i eth0 port 80
# Capture DNS queries
sudo tcpdump -i eth0 port 53
# Save capture to file
sudo tcpdump -i eth0 -w capture.pcap
# Read saved file
tcpdump -r capture.pcap
# View HTTP request/response content
sudo tcpdump -i eth0 -A port 80
# Capture only SYN packets (new connection monitoring)
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn) != 0'
strace
# Trace system calls
strace -p PID
# Trace only network-related calls
strace -e trace=network -p PID
# Trace file-related calls
strace -e trace=file ls
# Include timing information
strace -T -p PID
# Follow child processes
strace -f -p PID
# Save output to file
strace -o output.txt -p PID
lsof (List Open Files)
# Find process using a specific port
sudo lsof -i :80
# Files opened by a specific process
lsof -p PID
# Processes using a specific file
lsof /var/log/syslog
# Deleted but still open files (disk space not reclaimed)
lsof +L1
# Network connections
lsof -i -P -n
# Files opened by a specific user
lsof -u username
perf (Performance Counters)
# CPU profiling (10 seconds)
sudo perf record -g -p PID -- sleep 10
# View results
sudo perf report
# Real-time top functions
sudo perf top -p PID
# System-wide statistics
sudo perf stat -a -- sleep 5
# Generate flame graph
sudo perf record -g -p PID -- sleep 30
sudo perf script > out.perf
# Convert with FlameGraph tools
./stackcollapse-perf.pl out.perf > out.folded
./flamegraph.pl out.folded > flamegraph.svg
Comprehensive Troubleshooting Checklist
A step-by-step checklist for when network issues arise:
# 1. Check interface status
ip addr show
ip link show
# 2. Verify routing
ip route show
traceroute TARGET_HOST
# 3. Check DNS
dig TARGET_DOMAIN
nslookup TARGET_DOMAIN
# 4. Test connectivity
ping TARGET_HOST
curl -v http://TARGET_HOST
# 5. Check ports
ss -tuln
sudo lsof -i :PORT
# 6. Inspect firewall
sudo iptables -L -n
sudo nft list ruleset
# 7. Capture packets
sudo tcpdump -i eth0 host TARGET_HOST
# 8. Check system resources
top
free -h
df -h
# 9. Review logs
journalctl -xe
dmesg | tail
Conclusion
Here is a summary of what we covered:
- Networking Fundamentals: OSI/TCP/IP layered models, TCP handshake, flow/congestion control
- Web Protocols: Evolution from HTTP/1.1 to HTTP/3, TLS handshake
- DNS: Query process, record types, dig usage
- Linux Networking: Sockets, epoll, iptables/nftables, routing
- systemd: Unit files, service management, journalctl, timers
- Processes: fork/exec, zombies/orphans, cgroups, namespaces
- File Systems: VFS, inodes, ext4/XFS/btrfs, /proc, /sys
- Troubleshooting: ss, tcpdump, strace, lsof, perf
This knowledge is used daily in server operations, infrastructure management, and DevOps work. The key skill is being able to quickly identify which layer a problem originates from when issues arise. I recommend practicing each tool hands-on in a real environment to build solid proficiency.