💨

Kubernetes の TLS タイプの Secret リソースで TLS(SSL) 通信に必要なサーバー証明書と秘密鍵を管理する方法

に公開

概要

Kubernetes の Pod にデプロイした Nginx から TLS(SSL) 通信に必要なサーバー証明書や秘密鍵を参照したい時、方法はいくつか考えられる。例えば Pod のファイルシステムに直接証明書と秘密鍵を書き込む方法や、 TLS タイプの k8s Secret に証明書と秘密鍵を書き込む方法などである。

本記事では TLS タイプの k8s Secret リソースを作成し、Nginx Pod から参照する方法を試す。TLS 証明書と秘密鍵を安全に管理しつつ、コンテナ内で HTTPS 設定を行うことが可能なKubernetes ネイティブな手法である。

検証環境

  • macOS Sonoma 14.6.1 (minikube と openssl が動けば windows でも linux でも OK)
  • minikube v1.31.2
  • openssl 3.4.0

TLS タイプ k8s Secret リソースの作成

  1. サーバー証明書と秘密鍵の生成
    ローカル環境で OpenSSL を使用して自己署名証明書を生成
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
  -keyout ingress.key -out ingress.crt \
  -subj "/CN=example.com/O=example"
  1. k8s Secret リソースの作成
    生成した証明書ファイルを使用してTLS Secretを作成:
kubectl create secret tls tls-cert \
  --key ingress.key \
  --cert ingress.crt

Pod の作成

  1. Pod マニフェストの作成
    ボリュームマウント方式で Secret を参照する Pod を作成するためのマニュフェストファイルを作成。sample-nginx.yaml ファイルに下記内容を書き込む。
apiVersion: v1
kind: Pod
metadata:
  name: nginx-https
spec:
  containers:
  - name: nginx
    image: nginx:alpine
    volumeMounts:
    - name: tls-certs
      mountPath: "/etc/nginx/ssl"
      readOnly: true
  volumes:
  - name: tls-certs
    secret:
      secretName: tls-cert
  1. Pod 作成
kubectl apply -f sample-nginx.yaml

# 確認
kubectl get po

nginx の設定

  1. nginx 設定ファイルを修正して ssl 設定を追加
$ kubectl exec -it nginx-https -- vi /etc/nginx/conf.d/default.conf

# 追加部分
server {
    listen 443 ssl;
    ssl_certificate     /etc/nginx/ssl/tls.crt;
    ssl_certificate_key /etc/nginx/ssl/tls.key;
}

動作確認

  1. nginx プロセスを reload して設定を反映させた後、ポートフォワーディング実行
# リロード
$ kubectl exec -it nginx-https -- nginx -s reload
# ポートフォワーディング
$ kubectl port-forward nginx-https 8443:443

7. ローカルマシンで web ブラウザから https://localhost:8443 にアクセス。TLS 接続の警告をスキップし、nginx の画面が表示されれば成功。

(参考)
https://kubernetes.io/docs/concepts/configuration/secret/
https://stackoverflow.com/questions/69823769/provide-certificate-file-into-pod-in-k8s/69824237#69824237

Discussion