通过Init Container 解耦前端静态文件和nginx容器

通过Init Container 解耦前端静态文件和nginx容器

好处:

  • 初始容器可以利用Docker多阶段构建来生产出更小的镜像,因为只提供镜头文件,可以使部署更快
  • 讲Nginx作为主容器独立出来,方便统一管理升级
  • 解耦APP中静态文件和nginx,做到每个容器职责分离

示例

Dockerfile
FROM node:latest as builder
WORKDIR /data/project
RUN npm run build:pro

FROM alpine:3.14.2
WORKDIR /project/dist
COPY --from=builder /data/project/dist  ./
Deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: pro-app-nginx
  namespace: prod
  labels:
    app: pro-app-nginx
spec:
  selector:
    matchLabels:
      app: pro-app-nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: pro-app-nginx
    spec:
      imagePullSecrets:
         - name: harbor-registry
      volumes:
        # 1.与Ningx共享代码的.
        - name: shared-files
          emptyDir: {}
        # 2.持久化日志存储的
        - name: log-local-storage
          hostPath:
            path: /log/app/prod
        
      initContainers:
        - name: share-code
          image: pro-app-web:v2.3.7
          imagePullPolicy: Always
          args:
            - 'bash'
            - '-c'
            - 'cp -r /project/dist /var/www; chown nginx.nginx -R /var/www'
          volumeMounts:
            - name: shared-files
              mountPath: /var/www

        - name: nginx
          image: nginx:v1.20
          imagePullPolicy: IfNotPresent
          volumeMounts:
            - name: shared-files
              mountPath: /var/www
            - name: log-local-storage
              mountPath: /var/log/nginx
              subPath: pro-app-nginx
          ports:
            - containerPort: 80
              protocol: TCP
              name: nginx
          # livenessProbe:
          #   failureThreshold: 3
          #   initialDelaySeconds: 10
          #   periodSeconds: 60
          #   successThreshold: 1
          #   tcpSocket:
          #     port: 80
          #   timeoutSeconds: 2
          # readinessProbe:
          #   failureThreshold: 3
          #   initialDelaySeconds: 10
          #   periodSeconds: 60
          #   successThreshold: 1
          #   timeoutSeconds: 2
          #   tcpSocket:
          #     port: 80
          livenessProbe:
              failureThreshold: 3
              initialDelaySeconds: 10
              periodSeconds: 60
              successThreshold: 1
              httpGet:
                port: 80
                path: /health
              timeoutSeconds: 2
          readinessProbe:
            failureThreshold: 3
            initialDelaySeconds: 10
            periodSeconds: 60
            successThreshold: 1
            httpGet:
              port: 80
              path: /health
            timeoutSeconds: 2
          resources:
            limits:
              cpu: "800m"
              memory: 800Mi
            requests:
              cpu: "100m"
              memory: 100Mi

你可能感兴趣的:(kubernetes,前端,nginx,运维,Init,Container,k8s)