需求:k8s中建立5個nginx 的pod,通過service排程到不同的nginx pod,每個nginx pod有自己獨立的網頁内容,目的是能清晰的知道service通路排程到那個具體的pod上。
實作方式:通過Kubernetes 的 StatefulSet 和 Service 來實作這個需求。
準備網頁檔案
首先需要準備 5 個不同的網頁檔案,每個檔案對應一個 Nginx Pod。假設這 5 個檔案分别為 index1.html, index2.html, index3.html, index4.html, index5.html。
建立 ConfigMap
使用 ConfigMap 将這 5 個檔案打包為一個資源,并在 StatefulSet 中使用 volumeMounts 将資源挂載到相應的 Nginx Container 中。
以下是一個示例 ConfigMap YAML 檔案:
apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
index1.html: |
<html>
<body>
<h1>This is index1.html</h1>
</body>
</html>
index2.html: |
<html>
<body>
<h1>This is index2.html</h1>
</body>
</html>
index3.html: |
<html>
<body>
<h1>This is index3.html</h1>
</body>
</html>
index4.html: |
<html>
<body>
<h1>This is index4.html</h1>
</body>
</html>
index5.html: |
<html>
<body>
<h1>This is index5.html</h1>
</body>
</html>
上述 YAML 檔案将建立一個名為 nginx-config 的 ConfigMap,其中包含 5 個不同的網頁内容。可以使用以下指令來建立該 ConfigMap:
kubectl apply -f nginx-config.yaml
建立 StatefulSet
建立一個 StatefulSet 來建立 5 個 Nginx Pod,每個 Pod 挂載相應的網頁内容。
以下是一個示例 StatefulSet YAML 檔案:
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nginx-web
spec:
serviceName: nginx-web-service
replicas: 5
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
volumeMounts:
- name: nginx-config
mountPath: /usr/share/nginx/html
env:
- name: INDEX
valueFrom:
fieldRef:
fieldPath: metadata.name
ports:
- containerPort: 80
volumeClaimTemplates:
- metadata:
name: nginx-config
spec:
accessModes: [ "ReadWriteOnce" ]
storageClassName: "standard"
resources:
requests:
storage: 1Gi
上述 YAML 檔案将建立一個名為 nginx-web 的 StatefulSet。在 StatefulSet 的容器定義中,定義了 volumeMounts 以及使用 env 變量動态擷取 Pod 名稱,進而實作将不同的網頁内容挂載到不同的 Pod 中。可以使用以下指令将其應用到 Kubernetes 叢集中:
kubectl apply -f nginx-web.yaml
建立 Service
建立一個 Service 來将通路請求路由到這些 Nginx Pod。以下是一個示例 Service YAML 檔案:
apiVersion: v1
kind: Service
metadata:
name: nginx-web-service
spec:
selector:
app: nginx
ports:
- name: http
port: 80
targetPort: 80
該 YAML 檔案将建立一個名為 nginx-web-service 的 Service,并将其與 nginx-web StatefulSet 中的 Pod 關聯起來。該 Service 上的端口為 80。
可以使用以下指令來建立該 Service:
kubectl apply -f nginx-web-service.yaml
現在,您将擁有 5 個 Nginx Pod,每個 Pod 擁有自己獨立的網頁内容,并可以通過 Service 進行通路。