跳到主要内容

部署

2024年08月27日
柏拉文
越努力,越幸运

一、认识


为了在 Kubernetes (k8s) 中以生产环境的最佳实践部署 Nginx,我们需要创建一个包含 DeploymentServiceYAML 文件,此外,还应考虑使用 ConfigMapPersistentVolume 以满足生产环境的需求。

二、部署


2.1 配置 ConfigMap

ConfigMap 可以用来存储配置文件,允许你在不重新构建镜像的情况下更新配置。nginx-configmap.yaml 配置如下:

apiVersion: v1
kind: ConfigMap
metadata:
name: nginx-config
data:
nginx.conf: |
# 在这里放置你的 nginx.conf 内容
worker_processes auto;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
}

2.2 配置 PV 和 PVC

创建 PersistentVolumePersistentVolumeClaim(用于持久化存储)。nginx-pv-pvc.yaml 配置如下:

apiVersion: v1
kind: PersistentVolume
metadata:
name: nginx-pv
spec:
capacity:
storage: 1Gi
accessModes:
- ReadWriteMany
hostPath:
path: /mnt/data/nginx
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: nginx-pvc
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Gi

2.3 配置 Deployment

Deployment 中,我们将使用 ConfigMapPersistentVolumeClaim

apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
spec:
replicas: 2 # 生产环境通常会有多个副本以确保高可用性
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80
volumeMounts:
- name: config
mountPath: /etc/nginx/nginx.conf
subPath: nginx.conf
- name: data
mountPath: /usr/share/nginx/html
- name: logs
mountPath: /var/log/nginx
volumes:
- name: config
configMap:
name: nginx-config
- name: data
persistentVolumeClaim:
claimName: nginx-pvc
- name: logs
persistentVolumeClaim:
claimName: nginx-pvc

2.4 配置 Service

Nginx 服务暴露为一个 NodePortLoadBalancer,取决于你的环境。

apiVersion: v1
kind: Service
metadata:
name: nginx-service
spec:
type: NodePort
ports:
- port: 80
targetPort: 80
selector:
app: nginx

2.5 应用以上配置

使用 kubectl apply -f 命令来将以上 yaml 文件应用到 Kubernetes 集群中。

kubectl apply -f nginx-configmap.yaml
kubectl apply -f nginx-pv-pvc.yaml
kubectl apply -f nginx-deployment.yaml
kubectl apply -f nginx-service.yaml

使用 kubectl delete -f 命令来将以上应用删除

kubectl delete -f nginx-configmap.yaml
kubectl delete -f nginx-pv-pvc.yaml
kubectl delete -f nginx-deployment.yaml
kubectl delete -f nginx-service.yaml

使用 kubectl get pods 来检查 Pod 状态

kubectl get pods 

使用 kubectl describe pod nginx 来查看 Pod 运行日志

kubectl describe pod nginx

2.6 访问 Pod 容器

通过 kubectl exec -it nginx -- bash 来进入 Pod 容器,访问 Pod

kubectl exec -it nginx -- bash