Gateway
Gateway
A device that connects different networks. An API Gateway serves as the single entry point to microservices.
Gateway
A device that connects different networks. An API Gateway serves as the single entry point to microservices.
A gateway is a device or software that acts as a 'gate' connecting different networks, protocols, or systems. The router used at home is also a type of gateway, connecting the internal private network (192.168.x.x) with the external internet. A gateway can operate at every level of the OSI 7 layers, making it a higher-level concept than a router.
The key difference between a router and a gateway is the ability to translate protocols. A router forwards packets within the same protocol (mainly IP), whereas a gateway can translate between different protocols. For example, translating HTTP to MQTT or IPv4 to IPv6 is the role of a gateway. In practice, the Default Gateway refers to the first router that packets pass through when they leave the local network.
In cloud environments, gateways have become even more important. In AWS, the Internet Gateway (IGW) connects a VPC to the internet, and the NAT Gateway allows instances in a private subnet to access the external internet. While the IGW allows bidirectional communication and is free of charge, the NAT Gateway allows outbound traffic only and incurs about $0.045 per hour plus data processing costs.
An API Gateway serves as the single entry point for all API requests in a microservices architecture. Kong, AWS API Gateway, and Azure API Management are representative examples, and they provide features such as authentication/authorization, rate limiting (Rate Limiting), request routing, protocol translation, and logging/monitoring. Netflix switched from Zuul to Spring Cloud Gateway and handles billions of API requests per day.
import boto3
import netifaces
# 로컬 시스템의 기본 게이트웨이 확인
gateways = netifaces.gateways()
default_gw = gateways['default'][netifaces.AF_INET]
print(f"기본 게이트웨이: {default_gw[0]}") # 192.168.1.1
print(f"인터페이스: {default_gw[1]}") # eth0
# AWS: Internet Gateway 생성 및 연결
ec2 = boto3.client('ec2', region_name='ap-northeast-2')
# Internet Gateway 생성
igw = ec2.create_internet_gateway()
igw_id = igw['InternetGateway']['InternetGatewayId']
print(f"IGW 생성됨: {igw_id}")
# VPC에 연결
ec2.attach_internet_gateway(
InternetGatewayId=igw_id,
VpcId='vpc-12345678'
)
# NAT Gateway 생성 (퍼블릭 서브넷에 배치)
# 먼저 Elastic IP 할당
eip = ec2.allocate_address(Domain='vpc')
nat_gw = ec2.create_nat_gateway(
SubnetId='subnet-public-12345',
AllocationId=eip['AllocationId'],
TagSpecifications=[{
'ResourceType': 'natgateway',
'Tags': [{'Key': 'Name', 'Value': 'prod-nat-gw'}]
}]
)
print(f"NAT Gateway 생성됨: {nat_gw['NatGateway']['NatGatewayId']}")
# 라우팅 테이블 업데이트 (프라이빗 서브넷 → NAT Gateway)
ec2.create_route(
RouteTableId='rtb-private-12345',
DestinationCidrBlock='0.0.0.0/0',
NatGatewayId=nat_gw['NatGateway']['NatGatewayId']
)
# 로컬 시스템 게이트웨이 확인
# Linux/macOS
ip route | grep default # default via 192.168.1.1 dev eth0
netstat -rn | grep default # 라우팅 테이블 전체
# Windows
route print | findstr "0.0.0.0"
ipconfig | findstr "게이트웨이"
# AWS CLI: Internet Gateway 생성
aws ec2 create-internet-gateway \
--tag-specifications 'ResourceType=internet-gateway,Tags=[{Key=Name,Value=prod-igw}]'
# VPC에 IGW 연결
aws ec2 attach-internet-gateway \
--internet-gateway-id igw-12345678 \
--vpc-id vpc-12345678
# NAT Gateway 생성 (Elastic IP 필요)
aws ec2 allocate-address --domain vpc # EIP 할당
aws ec2 create-nat-gateway \
--subnet-id subnet-public-12345 \
--allocation-id eipalloc-12345678 \
--tag-specifications 'ResourceType=natgateway,Tags=[{Key=Name,Value=prod-nat}]'
# NAT Gateway 상태 확인 (available까지 2-3분 소요)
aws ec2 describe-nat-gateways \
--nat-gateway-ids nat-12345678 \
--query 'NatGateways[0].State'
# 프라이빗 서브넷 라우팅 테이블에 NAT Gateway 경로 추가
aws ec2 create-route \
--route-table-id rtb-private-12345 \
--destination-cidr-block 0.0.0.0/0 \
--nat-gateway-id nat-12345678
# Transit Gateway (여러 VPC 연결)
aws ec2 create-transit-gateway \
--description "Multi-VPC Hub" \
--options "AutoAcceptSharedAttachments=enable"
// Express.js API Gateway 패턴 구현
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const rateLimit = require('express-rate-limit');
const jwt = require('jsonwebtoken');
const app = express();
// Rate Limiting (분당 100 요청)
const limiter = rateLimit({
windowMs: 60 * 1000,
max: 100,
message: { error: 'Too many requests, please try again later' }
});
app.use(limiter);
// JWT 인증 미들웨어
const authMiddleware = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) return res.status(401).json({ error: 'No token provided' });
try {
req.user = jwt.verify(token, process.env.JWT_SECRET);
next();
} catch (err) {
res.status(403).json({ error: 'Invalid token' });
}
};
// 마이크로서비스 라우팅
const services = {
users: 'http://user-service:3001',
orders: 'http://order-service:3002',
products: 'http://product-service:3003'
};
// 각 서비스로 프록시
Object.entries(services).forEach(([path, target]) => {
app.use(`/api/${path}`, authMiddleware, createProxyMiddleware({
target,
changeOrigin: true,
pathRewrite: { [`^/api/${path}`]: '' },
onProxyReq: (proxyReq, req) => {
// 사용자 정보를 헤더에 추가
proxyReq.setHeader('X-User-Id', req.user.id);
proxyReq.setHeader('X-Request-Id', crypto.randomUUID());
},
onError: (err, req, res) => {
console.error(`Proxy error: ${err.message}`);
res.status(502).json({ error: 'Service unavailable' });
}
}));
});
// Health Check
app.get('/health', (req, res) => res.json({ status: 'ok' }));
app.listen(3000, () => console.log('API Gateway running on :3000'));
"Instances in the private subnet need to call external APIs, so we have to attach a NAT Gateway. However, a NAT Gateway is needed per AZ and costs $35 per month plus data processing costs, so if cost optimization is needed, consider a NAT Instance or a VPC Endpoint."
"Looking at why the EC2 instance can't connect to the internet: it's in a public subnet, but no Internet Gateway is attached to the VPC. Just attach an IGW and add a 0.0.0.0/0 → IGW route to the route table."
"Now that we have more than 10 microservices, we need to adopt an API Gateway. If we centralize unified authentication, Rate Limiting, and logging with Kong or AWS API Gateway, each service doesn't need to implement them redundantly. Also, clients only need to know a single endpoint, which makes management easier."
The IGW is for public subnets (bidirectional, free), and the NAT Gateway is for private subnets (outbound only, paid). Adding an IGW route to a private subnet will not provide internet connectivity. Be sure to use a NAT Gateway or a NAT Instance.
A NAT Gateway goes down together with its AZ in the event of an AZ failure. In production environments, deploy a NAT Gateway in each AZ, and route traffic so that the private subnet in each AZ uses the NAT Gateway in the same AZ.
Because all traffic passes through the API Gateway, the entire system goes down if it fails. Be sure to configure multi-AZ deployment, health checks, and Auto Scaling, and apply the circuit breaker pattern.
Public subnet: attach an IGW + assign public IPs. Private subnet: deploy a NAT Gateway per AZ. API Gateway: configure multi-AZ + Rate Limiting + timeout (29 seconds or less). Centralize VPC-to-VPC connectivity with a Transit Gateway.