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

Kong Gateway 재시작 없이 TLS 인증서 교체하기

원문 보기 위키 갱신

Kong Gateway 재시작 없이 TLS 인증서 교체하기 (Rotate TLS certificates without restarting Kong Gateway)

이 문서는 cert-manager를 사용해 Kong Gateway를 재시작하지 않고 TLS 인증서를 교체하는 방법을 알려줘요. Kong Ingress Controller가 cert-manager가 생성한 Secret을 Certificate와 SNI 엔티티로 변환하여 Admin API를 통해 전달하므로, 인증서 갱신 시 리로드나 재시작이 필요 없어요. kong.conf에 설정된 인증서는 시작 시 한 번만 읽히므로 재시작이 필요하다는 점도 함께 설명해요.

출처: 문서

본문

요약

cert-manager가 교체한 인증서를 Kong Gateway가 제공하게 하려면 어떻게 해야 해요? Gateway 리스너에서 cert-manager Secret을 참조하세요. Kong Ingress Controller는 Secret을 Certificate 및 SNI 엔티티로 변환하고 갱신할 때마다 Admin API를 통해 Kong Gateway로 푸시해요. 그래서 새 인증서가 리로드나 파드 재시작 없이 제공돼요. kong.conf에 설정된 인증서(예: ssl_cert)는 다르게 동작해요. 시작 시 한 번 읽히고 재시작이 필요해요.

사전 요구 사항

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 컨트롤 플레인 생성

Konnect API를 사용하여 새 CLUSTER_TYPE_K8S_INGRESS_CONTROLLER 컨트롤 플레인을 생성하세요:

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 리소스

이 방법 가이드에서는 클러스터에 몇 가지 Kubernetes 서비스가 필요해요. 이 서비스들은 이 방법 가이드에서 생성하는 리소스에 사용돼요.

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" }

cert-manager 설치

클러스터에 cert-manager를 설치하여 인증서를 자동으로 발급하고 교체하세요:

helm repo add jetstack https://charts.jetstack.io
helm repo update
helm upgrade --install \
  cert-manager jetstack/cert-manager \
  --namespace cert-manager \
  --create-namespace \
  --set crds.enabled=true
kubectl wait -n cert-manager --for=condition=ready pod --all --timeout=90s

cert-manager는 인증서를 갱신하고 새 키 쌍을 Kubernetes 시크릿에 기록해요. Kong Gateway가 새 인증서를 제공하기 시작하는지 여부는 처음에 인증서가 프록시에 도달한 방식에 따라 달라져요.

이 가이드에서는 cert-manager로 인증서를 발급하고, Gateway 리스너에서 제공하며, 갱신을 강제하고, Kong Gateway가 재시작 없이 새 인증서를 적용하는지 확인할 거예요.

Gateway 리스너에서 Secret을 참조하는 것이 자동 교체를 가능하게 해요. Kong Ingress Controller는 Secret을 감시하고 Certificate 및 SNI 엔티티로 변환하며, Kong Gateway는 구성 업데이트 시마다 이를 다시 읽어요. kong.conf를 통해 설정된 인증서는 다르게 동작해요. 자세한 내용은 인증서가 로드되고 다시 로드되는 시점을 참조하세요.

cert-manager 발급자 생성

Issuer 리소스는 인증서에 서명하는 인증 기관을 나타내요. kong 네임스페이스에 자체 서명 발급자를 생성하세요:

echo '
apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: selfsigned-issuer
  namespace: kong
spec:
  selfSigned: {}' | kubectl apply -f -

자체 서명 발급자는 이 가이드를 자체적으로 완결되게 해요. 프로덕션에서는 Let's Encrypt와 같은 ACME 발급자나 CA 발급자를 사용하세요. 모든 발급자 유형은 cert-manager 구성 문서를 참조하세요.

인증서 발급

demo.example.com 호스트 이름에 대한 Certificate를 생성하세요. cert-manager는 키 쌍을 demo.example.com이라는 Secret에 기록하고 만료 전에 자동으로 갱신해요:

echo '
apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: demo.example.com
  namespace: kong
spec:
  secretName: demo.example.com
  duration: 24h
  renewBefore: 12h
  issuerRef:
    name: selfsigned-issuer
    kind: Issuer
  dnsNames:
    - demo.example.com' | kubectl apply -f -

cert-manager가 인증서를 발급할 때까지 기다리고 Secret이 존재하는지 확인하세요:

kubectl wait --for=condition=Ready certificate/demo.example.com -n kong --timeout=90s
kubectl get secret demo.example.com -n kong

Secret이 세 개의 키와 함께 나열된 것을 볼 수 있어요:

NAME               TYPE                DATA   AGE
demo.example.com   kubernetes.io/tls   3      5s

{:.no-copy-code}

세 개의 키는 tls.crt, tls.key, ca.crt예요.

Secret을 참조하는 HTTPS 리스너 추가

Gateway에 TLS 리스너를 추가하고 certificateRefs가 cert-manager Secret을 가리키도록 하세요:

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"
              }]
            }
        }
    }
]'

이제 Kong Ingress Controller는 demo.example.com을 감시하고 cert-manager가 쓸 때마다 Certificate 엔티티를 다시 동기화해요.

리스너를 통해 트래픽 라우팅

https 리스너에 연결되고 사전 요구 사항에서 생성한 echo 서비스로 요청을 보내는 HTTPRoute를 생성하세요:

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'

현재 제공 중인 인증서 기록

  1. Kong Gateway가 demo.example.com에 대해 제시하는 인증서를 확인하고 일련번호와 유효 기간을 기록하세요:

    echo "" | openssl s_client -connect $PROXY_IP:443 -servername demo.example.com 2>/dev/null \
      | openssl x509 -noout -serial -dates -ext subjectAltName
    

    출력은 다음과 같아야 해요:

    serial=5B2C9A1E7F04D8B3A6E1C0F29D3847BA
    notBefore=Aug  7 10:12:04 2026 GMT
    notAfter=Aug  8 10:12:04 2026 GMT
    X509v3 Subject Alternative Name: critical
        DNS:demo.example.com
    

    {:.no-copy-code}

  2. Kong Gateway 파드가 실행된 시간을 기록해 두세요. 나중에 재시작되지 않았는지 확인할 수 있어요:

    kubectl get pods -n kong
    

인증서 교체

Secret을 삭제하여 cert-manager가 예정보다 일찍 새 인증서를 발급하도록 강제하세요. cert-manager는 Certificate에 더 이상 유효한 Secret이 없음을 감지하고 즉시 재발급합니다.

kubectl delete secret demo.example.com -n kong
kubectl wait --for=condition=Ready certificate/demo.example.com -n kong --timeout=90s

교체 확인

  1. 프록시에 다시 질의하세요:

    echo "" | openssl s_client -connect $PROXY_IP:443 -servername demo.example.com 2>/dev/null \
      | openssl x509 -noout -serial -dates -ext subjectAltName
    

    일련번호와 유효 기간이 변경되어야 합니다:

    serial=91F4D07C3A5B8E26D14903BC7E85A2FD
    notBefore=Aug  7 10:19:41 2026 GMT
    notAfter=Aug  8 10:19:41 2026 GMT
    X509v3 Subject Alternative Name: critical
        DNS:demo.example.com
    

    {:.no-copy-code}

  2. 어떤 파드도 재시작되지 않았는지 확인하세요:

    kubectl get pods -n kong
    

    RESTARTS 열의 값은 여전히 0이어야 합니다.

  3. 트래픽이 중단되지 않았는지 확인하세요:

    curl -sk --resolve demo.example.com:443:$PROXY_IP https://demo.example.com/echo -o /dev/null -w "%{http_code}\n"
    

    응답은 200이어야 합니다.

정리

생성된 Kubernetes 리소스 삭제

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

인증서 리소스 삭제

kubectl delete httproute echo -n kong
kubectl delete certificate demo.example.com -n kong
kubectl delete issuer selfsigned-issuer -n kong
kubectl delete secret demo.example.com -n kong --ignore-not-found

클러스터에서 Kong Ingress Controller 제거

helm uninstall kong -n kong

cert-manager 제거

helm uninstall cert-manager -n cert-manager
kubectl delete namespace cert-manager

FAQ

  • 내 배포가 이런 방식으로 교체되지 않는 인증서를 사용하는지 어떻게 확인하나요? kong.conf를 통해 설정된 인증서는 시작 시 한 번 읽히므로 여기에 설명된 교체 방식을 따르지 않아요. Kong Gateway 파드가 이 중 하나라도 설정했는지 확인하세요:

    kubectl get pods -n kong -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{range .spec.containers[*].env[*]}{"  "}{.name}{"="}{.value}{"\n"}{end}{end}' | grep -i "ssl_cert\|cluster_cert"
    

    명령이 아무것도 반환하지 않으면 배포의 모든 인증서가 자동으로 교체돼요. 프록시 인증서를 반환하는 경우 이 가이드에 표시된 대로 ssl_cert에서 Gateway 리스너로 이동하세요. 나머지의 경우 교체하려면 파드를 교체해야 해요. 자동화하려면 Kubernetes에서 Kong Gateway 재시작 또는 마운트된 인증서가 변경될 때 Kong Gateway 재시작을 참조하세요.

    이런 방식으로 동작하는 전체 매개변수 목록과 그 이유는 인증서가 로드되고 다시 로드되는 시점을 참조하세요.

관련 리소스

더 알아보기 (Learn more)