K8s快速建立自簽憑證的nginx

身為DevOps工程師
4 min readSep 23, 2023

--

這次遇到客戶的服務使用到了自簽的憑證,導致程式再呼叫時沒有辦法正常的使用。為了驗證程式修改後可以正常使用,就快速的使用K8s架設一座自簽憑證的Nginx。

Photo by Phil Shaw on Unsplash

前置條件

以下的操作你必須要先有Kubernetes 環境可以使用,如果沒有的話可以參考以下方式快速建立一台

  • Kind

https://kind.sigs.k8s.io/

  • minikube

https://minikube.sigs.k8s.io/docs/start/

開始吧!

Step 1. 產生TLS憑證

$ mkdir -p nginx
$ sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./nginx/nginx.key -out ./nginx/nginx.crt

Step 2. 建立nginx conf

為了讓Nginx知道我們要掛載TLS憑證與相關資訊,我們需要提供給Pod對應的設定檔。這部分使用K8s ConfigMap的方式來達成。

$ vim default.conf
server {
listen 443 ssl;

location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

server_name localhost;
ssl_certificate /etc/nginx/ssl/tls.crt;
ssl_certificate_key /etc/nginx/ssl/tls.key;
}

Step 3. 在Kubernetes上建立Configmap(nginx設定檔)

$ kubectl create configmap nginx-conf --from-file=default.conf

Step 4. 在Kubernetes上建立Secret(憑證)

將剛剛使用openssl產生的憑證建立成K8s Secret。

$ cd nginx
$ kubectl create secret tls nginx-tls --key nginx.key --cert nginx.crt

Step 5. 建立 nginx.yaml

在nginx YAML檔中,我們會掛載剛剛建立的ConfigMap與Secret。

$ vim nginx.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 1
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
volumes:
- name: tls-volume
secret:
secretName: nginx-tls
- name: config-volume
configMap:
name: nginx-conf
containers:
- name: nginx
image: nginx
ports:
- containerPort: 443
volumeMounts:
- mountPath: /etc/nginx/ssl
name: tls-volume
- mountPath: /etc/nginx/conf.d
name: config-volume

Step 6. 建立nginx pod

使用剛剛的YAML建立出Deployment

$ kubectl apply -f nginx.yaml

大功告成! 來測試看看吧!!

我們使用port-forward的方式直接將流量導入pod

# 取得Pod list
$ kubectl get po

# 本機的port 8787 轉發到 pod的port 443
$ kubectl port-forward pod/<nginx_pod_name> 8787:443s

Reference

  • Kubernetes NGINX https Service

https://mpolinowski.github.io/docs/DevOps/Kubernetes/2019-01-21--kubernetes-nginx-https-service/2019-01-21/

--

--

身為DevOps工程師

目前在蓋亞資訊擔任DevOps Consultant。最近才從後端的世界轉成投向DevOps的懷抱,目前專注在Kubernetes, GitLab, DevSecOps的學習中。