🌍 Networking

Port Forwarding

Port Forwarding

A technique that forwards port traffic on a router or firewall to an internal IP so that external users can reach a specific device or service on an internal network. Essential for exposing a local server externally in a NAT environment.

📖 Detailed Explanation

Port Forwarding is a networking technique that forwards traffic arriving at a specific port from an external network to a designated IP address and port on the internal network. The routers used at home or in the office let multiple devices use the Internet through a single public IP via NAT (Network Address Translation), and in this setup, port forwarding configuration is required to reach an internal server from the outside.

In a NAT environment, internal devices use private IPs (192.168.x.x, 10.x.x.x, etc.). Since these private IPs cannot be accessed directly from the outside, you set a rule on the router such as "when traffic arrives from outside on port 80, send it to internal 192.168.0.100:80." This is the essence of port forwarding. It is like calling a company's main number and being connected to an extension.

There are several types of port forwarding. Local Port Forwarding connects a local port to a port on a remote server through an SSH tunnel. Remote Port Forwarding connects a port on a remote server to a local service, allowing the local server to be accessed from the outside. Dynamic Port Forwarding behaves like a SOCKS proxy and tunnels all traffic.

In modern development environments, port forwarding is used in many ways. You expose a local development server externally for webhook testing or client demos (ngrok, Cloudflare Tunnel), run media servers, NAS, and game servers on a home server, and securely connect to a database behind a firewall through an SSH tunnel. In cloud environments, you can also access a Pod directly with Kubernetes' kubectl port-forward command.

💻 Code Example

# SSH 로컬 포트 포워딩
# 로컬 3306 포트를 원격 서버를 경유해 DB 서버 3306에 연결
ssh -L 3306:db-server.internal:3306 user@bastion.example.com

# 실사용 예: 로컬에서 MySQL 클라이언트로 접속
mysql -h 127.0.0.1 -P 3306 -u dbuser -p

# SSH 리모트 포트 포워딩 (역방향)
# 원격 서버의 8080 포트로 들어오는 요청을 로컬 3000으로 전달
# 외부에서 bastion:8080 접속 시 내 로컬 개발 서버(3000)에 연결
ssh -R 8080:localhost:3000 user@bastion.example.com

# 다이나믹 포트 포워딩 (SOCKS 프록시)
# 로컬 9090을 SOCKS5 프록시로 사용
ssh -D 9090 user@remote-server.com
# 브라우저에서 SOCKS5 프록시 localhost:9090 설정

# 백그라운드에서 SSH 터널 유지
ssh -f -N -L 5432:localhost:5432 user@server.com
# -f: 백그라운드 실행
# -N: 원격 명령 실행 안 함 (터널만 유지)

# 여러 포트 동시 포워딩
ssh -L 3306:db:3306 -L 6379:redis:6379 -L 5432:postgres:5432 user@bastion

# autossh로 끊김 없는 터널 유지 (자동 재연결)
autossh -M 0 -f -N -L 3306:db:3306 user@bastion.example.com
# Linux iptables를 이용한 포트 포워딩
# 전제: IP 포워딩 활성화
echo 1 > /proc/sys/net/ipv4/ip_forward
# 영구 설정: /etc/sysctl.conf에 net.ipv4.ip_forward=1 추가

# 외부 80 포트 → 내부 192.168.1.100:8080으로 포워딩
# PREROUTING: 패킷이 라우팅되기 전에 목적지 변경
iptables -t nat -A PREROUTING -p tcp --dport 80 \
    -j DNAT --to-destination 192.168.1.100:8080

# FORWARD 체인에서 해당 트래픽 허용
iptables -A FORWARD -p tcp -d 192.168.1.100 --dport 8080 -j ACCEPT

# MASQUERADE: 내부에서 외부로 나갈 때 출발지 IP 변환
iptables -t nat -A POSTROUTING -j MASQUERADE

# 현재 NAT 규칙 확인
iptables -t nat -L -n -v

# 특정 규칙 삭제
iptables -t nat -D PREROUTING -p tcp --dport 80 \
    -j DNAT --to-destination 192.168.1.100:8080

# 규칙 저장 (Ubuntu/Debian)
iptables-save > /etc/iptables/rules.v4

# nftables (최신 Linux의 iptables 대체)
nft add rule nat prerouting tcp dport 80 dnat to 192.168.1.100:8080

# firewalld (CentOS/RHEL)
firewall-cmd --zone=public --add-forward-port=port=80:proto=tcp:toport=8080:toaddr=192.168.1.100 --permanent
firewall-cmd --reload
# ngrok - 로컬 서버를 공인 URL로 노출 (가장 간단)
# 설치: brew install ngrok 또는 https://ngrok.com에서 다운로드
ngrok http 3000  # 로컬 3000 포트를 인터넷에 공개
# 결과: https://abc123.ngrok.io → localhost:3000

# 커스텀 도메인 사용 (유료)
ngrok http --domain=my-app.ngrok.io 3000

# TCP 포트 포워딩 (SSH, DB 등)
ngrok tcp 22  # 로컬 SSH를 외부에서 접근 가능하게

# Cloudflare Tunnel (무료, 더 안정적)
# 1. cloudflared 설치
brew install cloudflared  # macOS
# 2. 터널 생성 및 인증
cloudflared tunnel login
cloudflared tunnel create my-tunnel
# 3. 로컬 서버 노출
cloudflared tunnel --url http://localhost:3000

# Kubernetes port-forward
# Pod에 직접 접근 (디버깅용)
kubectl port-forward pod/my-app-pod 8080:80
# 이제 localhost:8080 → Pod의 80 포트

# Service를 통한 포트 포워딩
kubectl port-forward svc/my-service 3000:80

# Docker 포트 매핑 (-p 플래그)
docker run -p 8080:80 nginx  # 호스트 8080 → 컨테이너 80
docker run -p 127.0.0.1:8080:80 nginx  # 로컬호스트만 접근 허용

🗣️ Say It Like This in Practice

💬 In a home server setup consultation
"To run a NAS or media server at home, you need to configure port forwarding on the router. Find the 'Virtual Server' or 'Port Forwarding' menu in the router's admin page and connect external port 8080 to port 8080 of the internal NAS IP. However, for security, use a unique port number rather than the default ports (21, 22, 80), and if possible set up a VPN."
💬 In a development meeting
"To test a Stripe webhook, the local server must be reachable from outside, and ngrok makes it simple. Running 'ngrok http 3000' generates a public URL, and you register that as the webhook endpoint in the Stripe Dashboard. When development is done, switching to Cloudflare Tunnel is also good, since it's free and more stable."
💬 In infrastructure troubleshooting
"You can't access the production DB directly, so you have to go in through an SSH tunnel. Run 'ssh -L 5432:prod-db.internal:5432 bastion', then connect to localhost:5432 in DBeaver. Under the firewall policy only the bastion server is allowed DB access, so this method is the safest and also leaves audit logs."

⚠️ Common Mistakes & Cautions

❌
Exposing default ports externally as is

Opening default ports such as SSH (22), RDP (3389), and MySQL (3306) as is makes you a target for automated bot attacks. Map external ports to non-standard ports such as 30022 and 33389, and defend against brute-force attacks with tools like fail2ban.

❌
Opening all ports with a DMZ setting

A router's DMZ feature exposes all ports of a specific IP to the outside. It is convenient but very dangerous, so forward only the necessary ports individually. Use DMZ only as a last resort, and always configure the firewall on that device.

❌
Router firmware UPnP security vulnerabilities

UPnP (Universal Plug and Play) lets apps configure port forwarding automatically, but malicious programs can also abuse it. If possible, disable UPnP and configure port forwarding manually.

✅
Proper port forwarding security settings

The safest approach is to first connect to the internal network through a VPN (WireGuard, OpenVPN) and then access the services. If that is not possible, allow only specific IPs on the firewall and apply strong authentication (SSH keys, MFA) to every service.

🔗 Related Terms

📚 Learn More