In Kubernetes, when a Pod finishes its execution (either because the container process naturally terminates or due to a failure), the Pod object typically remains in the cluster. This allows you to inspect the status of the Pod, examine logs, and perform other post-mortem analyses.
However, the Pod's containers are stopped, and no new containers will be started unless the Pod is controlled by a higher-level controller, such as a Job or a Deployment, which may restart or replace the Pod depending on the policy.
If you want to ensure that the Pod and its containers remain for a few minutes after completion or failure, you would typically use a Job resource rather than creating a standalone Pod. Jobs are designed for tasks that are expected to terminate, and they have a feature to keep finished Pods around for a specified duration.
Here is an example Job definition in YAML that will keep the Pod around for 300 seconds (5 minutes) after completion or failure:
apiVersion: batch/v1
kind: Job
metadata:
name: example-job
spec:
template:
spec:
containers:
- name: example-container
image: busybox
command: ["sh", "-c", "echo Hello, Kubernetes! && sleep 30"]
restartPolicy: Never
backoffLimit: 0
ttlSecondsAfterFinished: 300
In this Job definition:
spec.template: This section defines the Pod template for the Job.
spec.template.spec.containers: This section lists the containers that will run in the Pod.
spec.template.spec.restartPolicy: This is set to Never because we don't want Kubernetes to restart the containers when they exit. Alternatives are Always and OnFailure.
spec.backoffLimit: This defines the number of retries before considering a Job as failed. Setting it to 0 means no retries after the first failure.
spec.ttlSecondsAfterFinished: This field specifies the duration in seconds that the Job should be retained after finishing. In this case, it's set to 300 seconds, which means the Pod will remain for 5 minutes after completion or failure before Kubernetes deletes it.
Please note that the ttlSecondsAfterFinished feature might not be enabled by default in all Kubernetes clusters, especially in older versions. It is a feature of the Kubernetes Job controller that requires enabling the TTLAfterFinished feature gate. If this feature gate is not enabled, you may need to manually clean up the Pods or use a workaround, such as setting up a cron job to delete finished Pods based on labels or statuses after a certain amount of time.