본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

TLS 종료로 HTTPS 트래픽 프록시하기

원문 보기 위키 갱신

TLS 종료로 HTTPS 트래픽 프록시하기 (TLS Termination)

이 문서에서는 Kong Ingress Controller에서 TLS 인증서로 HTTPS 요청을 종료하고 라우팅하는 방법을 안내해요. HTTPRoute나 Ingress 리소스를 만들면 Kong이 이를 Gateway Service와 Route로 변환해 줘요. 쿠버네티스 Secret에 담긴 TLS 인증서를 지정하면 Kong Gateway가 HTTPS 요청을 대신 처리해 준답니다. Konnect 배포와 온프레미스 배포 두 가지 환경에 맞는 절차를 모두 확인해 봐요.

출처: 문서

본문

TL;DR

Kong Ingress Controller로 HTTPS 트래픽을 라우팅하려면 어떻게 해야 하나요? HTTPRoute 또는 Ingress 리소스를 만들면, 이 리소스가 Kong Gateway Service와 Route로 변환돼요. Kong Gateway로 HTTPS 요청을 종료하려면 TLS 인증서가 담긴 Kubernetes Secret을 지정하세요.

사전 준비

Konnect 배포: Kong Konnect

Konnect 계정이 없다면, 온보딩 마법사를 통해 빠르게 시작할 수 있어요.

  1. 이 튜토리얼을 완료하려면 다음의 Konnect 항목들이 필요해요:

    • 개인 액세스 토큰(PAT): Konnect PAT 페이지를 열고 Generate Token을 선택해 새 개인 액세스 토큰을 만드세요.
  2. 개인 액세스 토큰을 환경 변수로 설정하세요:

    export KONNECT_TOKEN='YOUR KONNECT TOKEN'
    

Gateway API 활성화

  1. Kong Ingress Controller를 설치하기 전에 Gateway API CRD를 설치하세요.

    kubectl apply -f https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.1/standard-install.yaml
    

    {: data-test-prereq="block" }

  2. 사용할 Gateway와 GatewayClass 인스턴스를 만드세요.

    echo "
    apiVersion: v1
    kind: Namespace
    metadata:
      name: kong
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: GatewayClass
    metadata:
      name: kong
      annotations:
        konghq.com/gatewayclass-unmanaged: 'true'
    spec:
      controllerName: konghq.com/kic-gateway-controller
    ---
    apiVersion: gateway.networking.k8s.io/v1
    kind: Gateway
    metadata:
      name: kong
    spec:
      gatewayClassName: kong
      listeners:
      - name: proxy
        port: 80
        protocol: HTTP
        allowedRoutes:
          namespaces:
            from: All
    " | kubectl apply -n kong -f -
    

    {: data-test-prereq="block" }

Konnect 배포: KIC Control Plane 생성

Konnect API를 사용해 새로운 CLUSTER_TYPE_K8S_INGRESS_CONTROLLER Control Plane을 만드세요:

CONTROL_PLANE_DETAILS=$(curl -X POST "https://us.api.konghq.com/v2/control-planes" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "name": "My KIC CP",
       "cluster_type": "CLUSTER_TYPE_K8S_INGRESS_CONTROLLER"
     }'
)

나중에 values.yaml 파일을 작성할 때 id와 telemetry_endpoint가 필요해요. 환경 변수로 저장해 두세요:

CONTROL_PLANE_ID=$(echo $CONTROL_PLANE_DETAILS | jq -r .id)
CONTROL_PLANE_TELEMETRY=$(echo $CONTROL_PLANE_DETAILS | jq -r '.config.telemetry_endpoint | sub("https://";"")')

mTLS 인증서 생성

Kong Ingress Controller는 TLS 인증서로 보호되는 연결을 통해 Konnect와 통신해요.

openssl을 사용해 새 인증서를 생성하세요:

openssl req -new -x509 -nodes -newkey rsa:2048 -subj "/CN=kongdp/C=US" -keyout ./tls.key -out ./tls.crt

curl로 Konnect API에 인증서를 전송하려면 인증서가 한 줄짜리 문자열이어야 해요. awk를 사용해 인증서를 포맷하세요:

export CERT=$(awk 'NF {sub(/\r/, ""); printf "%s\\n",$0;}' tls.crt);

다음으로, 인증서를 Konnect에 업로드하세요:

curl -X POST "https://us.api.konghq.com/v2/control-planes/$CONTROL_PLANE_ID/dp-client-certificates" \
     --no-progress-meter --fail-with-body  \
     -H "Authorization: Bearer $KONNECT_TOKEN" \
     --json '{
       "cert": "'$CERT'"
     }'

마지막으로, Kong Ingress Controller가 읽을 수 있도록 인증서를 Kubernetes 시크릿에 저장하세요:

kubectl create namespace kong -o yaml --dry-run=client | kubectl apply -f -
kubectl create secret tls konnect-client-tls -n kong --cert=./tls.crt --key=./tls.key

Konnect 배포: Kong Ingress Controller 실행 (Konnect에 연결)

  1. Kong Helm 차트를 추가하세요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. values.yaml 파일을 만드세요:

    cat <<EOF > values.yaml
    controller:
      ingressController:
        image:
          tag: "3.5"
        env:
          feature_gates: "FillIDs=true"
        konnect:
          license:
            enabled: true
          enabled: true
          controlPlaneID: "$CONTROL_PLANE_ID"
          tlsClientCertSecretName: konnect-client-tls
          apiHostname: "us.kic.api.konghq.com"
    gateway:
      image:
        repository: kong
        tag: "3.9.3"
      env:
        konnect_mode: 'on'
        vitals: "off"
        cluster_mtls: pki
        cluster_telemetry_endpoint: "$CONTROL_PLANE_TELEMETRY:443"
        cluster_telemetry_server_name: "$CONTROL_PLANE_TELEMETRY"
        cluster_cert: /etc/secrets/konnect-client-tls/tls.crt
        cluster_cert_key: /etc/secrets/konnect-client-tls/tls.key
        lua_ssl_trusted_certificate: system
        proxy_access_log: "off"
        dns_stale_ttl: "3600"
      secretVolumes:
         - konnect-client-tls
    EOF
    

    {: data-test-prereq="block" }

  3. Helm으로 Kong Ingress Controller를 설치하세요:

    helm install kong kong/ingress -n kong --create-namespace --values ./values.yaml --wait 
    

    {: data-test-prereq="block" }

  4. 이후 명령어에서 사용할 수 있도록 $PROXY_IP를 환경 변수로 설정하세요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

온프레미스 배포: Kong Ingress Controller 실행

  1. Kong Helm 차트를 추가하세요:

    helm repo add kong https://charts.konghq.com
    helm repo update
    
  2. Helm으로 Kong Ingress Controller를 설치하세요:

    helm install kong kong/ingress -n kong --create-namespace --wait 
    

    {: data-test-prereq="block" }

  3. 이후 명령어에서 사용할 수 있도록 $PROXY_IP를 환경 변수로 설정하세요:

    export PROXY_IP=$(kubectl get svc --namespace kong kong-gateway-proxy -o jsonpath='{range .status.loadBalancer.ingress[0]}{@.ip}{@.hostname}{end}')
    echo $PROXY_IP
    

필요한 Kubernetes 리소스

이 how-to를 진행하려면 클러스터에서 몇 가지 Kubernetes 서비스를 사용할 수 있어야 해요. 이 how-to에서 만드는 리소스가 이 서비스들을 사용하게 돼요.

kubectl apply -f https://developer.konghq.com/manifests/kic/echo-service.yaml -n kong

{: data-test-prereq="block" }

서비스 파드가 준비될 때까지 기다리세요:

kubectl wait --for=condition=Ready pod --all -n kong --timeout=300s

{: data-test-prereq="block" }

TLS 인증서 생성

  1. demo.example.com 호스트명용 테스트 인증서를 만드세요. 이 인증서는 TLS 트래픽을 보호하는 데 사용돼요.

    OpenSSL 1.1.1+

    openssl req -subj '/CN=demo.example.com' -new -newkey rsa:2048 -sha256 \
      -days 365 -nodes -x509 -keyout server.key -out server.crt \
      -addext "subjectAltName = DNS:demo.example.com" \
      -addext "keyUsage = digitalSignature" \
      -addext "extendedKeyUsage = serverAuth" 2> /dev/null;
      openssl x509 -in server.crt -subject -noout
    

    {: data-test-step="block"}

    OpenSSL 0.9.8

    openssl req -subj '/CN=demo.example.com' -new -newkey rsa:2048 -sha256 \
      -days 365 -nodes -x509 -keyout server.key -out server.crt \
      -extensions EXT -config <( \
       printf "[dn]\nCN=demo.example.com\n[req]\ndistinguished_name = dn\n[EXT]\nsubjectAltName=DNS:demo.example.com\nkeyUsage=digitalSignature\nextendedKeyUsage=serverAuth") 2>/dev/null;
      openssl x509 -in server.crt -subject -noout
    

    macOS Monterey에서 제공되는 버전을 포함한 구버전 OpenSSL에서는 이 명령어의 대체 버전을 사용해야 해요.

  2. 인증서가 담긴 Secret을 만드세요:

    kubectl create secret -n kong tls demo.example.com --cert=./server.crt --key=./server.key
    

    {: data-test-step="block"}

HTTPS 트래픽 라우팅

HTTPS 트래픽을 수신하려면 Gateway 리소스에 TLS 리스너를 추가로 설정하세요:

kubectl patch -n kong --type=json gateway kong -p='[
    {
        "op":"add",
        "path":"/spec/listeners/-",
        "value":{
            "name": "https",
            "port": 443,
            "protocol":"HTTPS",
            "hostname":"demo.example.com",
            "allowedRoutes": {
              "namespaces": {
                "from": "All"
              }
            },
            "tls": {
              "mode": "Terminate",
              "certificateRefs":[{
                "group":"",
                "kind":"Secret",
                "name":"demo.example.com"
              }]
            }
        }
    }
]'

{: data-test-step="block"}

HTTPRoute 생성

HTTP 트래픽을 라우팅하려면 Kubernetes Service를 가리키는 HTTPRoute 또는 Ingress 리소스를 만들어야 해요.

Gateway API

echo "
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
  name: echo
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  parentRefs:
  - name: kong
    namespace: kong
    sectionName: https
  rules:
  - matches:
    - path:
        type: PathPrefix
        value: '/echo'
    backendRefs:
    - name: echo
      kind: Service
      port: 1027
  hostnames:
  - demo.example.com
" | kubectl apply -f -

{: data-test-step="block" }

Ingress

echo "
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: echo
  namespace: kong
  annotations:
    konghq.com/strip-path: 'true'
spec:
  ingressClassName: kong
  tls:
  - secretName: demo.example.com
    hosts:
    - demo.example.com
  rules:
  - host: demo.example.com
    http:
      paths:
      - path: '/echo'
        pathType: ImplementationSpecific
        backend:
          service:
            name: echo
            port:
              number: 1027
" | kubectl apply -f -

설정 검증

httproute가 True 상태가 될 때까지 기다리세요.

kubectl wait -n kong --timeout=30s httproute/echo \
  --for='jsonpath={.status.parents[?(@.parentRef.name=="kong")].conditions[?(@.type=="Programmed")].status }=True'

리소스가 조정(reconcile)되고 나면 /echo 엔드포인트를 호출할 수 있고, Kong Gateway가 요청을 echo 서비스로 라우팅해요.

Konnect 배포

curl -k "https://$PROXY_IP/echo" \
     --no-progress-meter --fail-with-body  \
     -H "Host: demo.example.com"

온프레미스 배포

curl -k "https://$PROXY_IP/echo" \
     --no-progress-meter --fail-with-body  \
     -H "Host: demo.example.com"

정리

생성한 Kubernetes 리소스 삭제

kubectl delete -n kong -f https://developer.konghq.com/manifests/kic/echo-service.yaml

클러스터에서 KIC 제거

helm uninstall kong -n kong

더 알아보기 (Learn more)

  • HTTPRoute나 Ingress가 변환되는 Kong의 핵심 개체가 어떤 역할을 하는지 살펴보세요 — Kong Gateway Service
  • TLS 종료 후 트래픽이 실제로 전달되는 라우팅 규칙 개체예요 — Route
  • Konnect 계정이 아직 없다면 이 온보딩 마법사로 빠르게 시작할 수 있어요 — onboarding wizard
  • Konnect API 호출에 필요한 개인 액세스 토큰(PAT)을 발급받는 페이지예요 — Konnect PAT page