Home > Software engineering >  Kubernetes delete POD with hostPath data files
Kubernetes delete POD with hostPath data files

Time:11-07

I am new to Kubernetes, I am creating POD on run time to push data and after pushing and collecting data I am deleting POD.

For the processing of files I have connected SSD. and assigned its path as hostPath: /my-drive/example while creating POD. Now when i run my POD i can see the files in defined path.

But, Now I just wanted to delete files created by POD in a hostPath directory while deleting POD. is it possible?

My POD file looks like.

apiVersion: v1
kind: Pod
metadata:
  name: pod-example
  labels:
    app: pod-example
spec:
  containers:
  - name: pod-example
    image: "myimage.com/abcd:latest"
    imagePullPolicy: Always
    workingDir: /pod-example
    env:
    volumeMounts:
    - name: "my-drive"
      mountPath: "/my-drive"
  volumes:
  - name: "my-drive"
    persistentVolumeReclaimPolicy: Recycle
    hostPath:
      path: /my-drive/example
  restartPolicy: Never
  imagePullSecrets:
  - name: regcred
  affinity:
    podAntiAffinity:
      requiredDuringSchedulingIgnoredDuringExecution:
      - labelSelector:
          matchExpressions:
          - key: "kubernetes.io/hostname"
            operator: In
            values:
            - my-node
        topologyKey: "kubernetes.io/hostname"

CodePudding user response:

Update persistentVolumeReclaimPolicy to Delete as shown below

persistentVolumeReclaimPolicy: Delete

CodePudding user response:

You can achieve this by using lifecycle hooks in K8s. Under them, preStop hook can be used here since you need to do action when stopping the pod.

Check docs related to lifecycle hooks: https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/

If you exact know the files or let's say a directory to delete, you can use Exec hook hanlder. Check the sample below that I've added for your reference.

lifecycle:
  preStop:
    exec:
      command:
        - "sh"
        - "-c"
        - >
          echo "Deleting files in my-drive/example/to-be-deleted" > /proc/1/fd/1 # Add preStop hook's stdout to main process's stdout
          rm -r my-drive/example/to-be-deleted

P.S. According to your problem statement, you are not using the POD continuously it seems. If the task that you are looking is to execute periodically or not continuous, I would suggest you to select either K8s CronJob or Job rather a POD. Make sure to have required user access inside the container to delete files/floders.

  • Related