Understanding Container Workloads
Containerized workloads are typically classified into two categories:- Long-running workloads: For example, web servers and database applications that continue to run until they are manually stopped.
- Batch processing tasks: These execute a specific operation—such as computation, image processing, data analysis, or report generation—and then terminate.
Simple Workload Example in Docker
When you run a Docker container tasked with a basic math operation—like adding two numbers—the container starts, performs the calculation, prints the output, and then exits. For example:Replicating the Task in Kubernetes
To replicate the math addition in Kubernetes, you first need to create a pod definition file. When this pod is created, it launches a container that performs the computation and exits. Here is the pod definition:Setting the restart policy to Never ensures that the pod does not restart automatically after the command has completed, which is ideal for one-off tasks.
Introducing Jobs for Batch Processing
For batch processing or large-scale data tasks, you might need multiple pods working together concurrently. Unlike ReplicaSets, which ensure a certain number of pods remain running, Kubernetes Jobs are designed to run pods until the specified task is completed successfully. To create a Job, start with a job definition file that uses the API versionbatch/v1 and kind Job. In the job specification, a template holds the pod definition. Here’s an example job definition that performs our math addition:
kubectl logs command with the pod name.
To delete the job along with its associated pods, run:
Running Multiple Pods with Job Completions
In many real-world scenarios, you might require a job to run multiple pods simultaneously to process data in parallel or handle retries for failed operations. To run three pods for a single job, set thecompletions field to 3:
Handling Failures with Jobs
Consider a scenario where you use an image likekodekloud/random-error that randomly either completes successfully or fails. In such cases, if one pod fails, Kubernetes will create another pod until it achieves the specified number of successful completions.
Here is an example job definition to handle this scenario:
Running Pods in Parallel with Jobs
For scenarios where you want the pods to run concurrently, you can set theparallelism property. This allows multiple pods to be created simultaneously. For example, to run up to three pods in parallel:
Kubernetes Jobs are ideal for managing batch tasks where tasks must complete successfully before termination. They allow for sequential or parallel pod execution and include robust failure handling.