initContainer 使用案例

  1. 将glusterfs存储同时挂载到initContainer和container的指定目录上,如:/var/data/
  2. 在initContainer中拉取资源放到/var/data/,也就推到了分布式存储glusterfs上,如:

    wget -P /var/data/ http://127.0.0.1:8081/repository/k8s/kubectl/kubectl-v1.10.0-linux-amd64.tar.gz
  3. 这样当业务容器启动后,就可以在指定目录/var/data下看到initContainer拉取到的资源
  4. 在initContainer中,最好增加一部检测指定资源是否存在,以防重复拉取,如:

    if [ ! -f "/var/data/kubectl-v1.10.0-linux-amd64.tar.gz" ]; then wget -P /var/data/ http://127.0.0.1:8081/repository/k8s/kubectl/kubectl-v1.10.0-linux-amd64.tar.gz; fi
apiVersion: apps/v1
kind: Deployment
metadata:
  name: mysql
spec:
  replicas: 1
  selector:
    matchLabels:
      name: mysql
  template:
    metadata:
      labels:
        name: mysql
    spec:
      initContainers:
      - name: getresource
        image: busybox:v0.1.0
        command: ['sh', '-c', 'wget -P /var/data/ http://127.0.0.1:8081/repository/k8s/kubectl/kubectl-v1.10.0-linux-amd64.tar.gz ']
        volumeMounts:
        - name: mysql-pvc
          mountPath: /var/data
      containers:
      - name: mysql
        image: percona:5.7.22
        imagePullPolicy: Always
        ports:
        - containerPort: 3306
        resources:
          limits:
            memory: "500Mi"
            cpu: "500m"
          requests:
            memory: "500Mi"
            cpu: "250m"
        env:
        - name: MYSQL_ROOT_PASSWORD
          value: "mysql"
        volumeMounts:
        - name: mysql-pvc
          mountPath: /var/data
      volumes:
       - name: mysql-pvc
         persistentVolumeClaim:
           claimName: mysql
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mysql
spec:
  accessModes:
  - ReadWriteMany
  resources:
    requests:
      storage: "5Gi"
  volumeName: 
  storageClassName: glusterfs
---
kind: Service
apiVersion: v1
metadata:
  name: mysql
spec:
  type: ClusterIP
  ports:
  - name: mysql
    port: 3306
    targetPort: 3306
    protocol: TCP
  selector:
    name: mysql

相关推荐