Skip to content
ImagineWorld

Getting Started with Kubernetes in the Cloud

node_idnode-book_kubernetes-for-generative-ai-solutions_chapter-03-getting-started-with-kubernetes-in-the-cloud
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleGetting Started with Kubernetes in the Cloud
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 3 — Getting Started with Kubernetes in the Cloud

Section titled “Chapter 3 — Getting Started with Kubernetes in the Cloud”

Cloud computing has revolutionized how organizations access scalable IT resources, enabling the fast deployment of compute, storage, and networking services. For teams adopting containerized applications, Kubernetes (K8s) has become the de facto platform. Cloud providers offer managed K8s services, such as Amazon Elastic Kubernetes Service (EKS), Google Kubernetes Engine (GKE), and Azure Kubernetes Service (AKS), which makes it easier to run and deploy GenAI models.

In this chapter, we’ll discuss how the cloud can help simplify the management of production-grade K8s clusters by offloading some of their complexities. Then, we’ll guide you in creating your first cluster using infrastructure automation.

Let’s explore the following key topics:

  • Advantages of running K8s in the cloud
  • Setting up a K8s cluster in the cloud
  • Deploying our first GenAI model in the K8s cluster

A report published in 2023, Kubernetes in the wild report 2023 (https://www.dynatrace.com/news/blog/kubernetes-in-the-wild-2023/), states that the number of K8s clusters in the cloud grew about five times as fast as the clusters hosted on-premises at the same time. This is primarily attributed to the following factors:

  • Managed services: Operating a production-grade K8s cluster typically involves ensuring there’s a highly available control plane, cluster management activities such as creating, upgrading, and patching all K8s control plane and data plane components, resource management, security, monitoring, and more. Many of these activities add significant operational overhead, which is undifferentiated and takes time and resources away from core business operations. Due to this, many K8s consumers have chosen to offload the undifferentiated heavy lifting of managing K8s clusters by choosing one of the managed offerings that’s available. Some of the notable managed K8s offerings are as follows:
    • Amazon EKS: This is a managed service that’s used to run K8s in the AWS cloud and on-premises data centers. With Amazon EKS, you can take advantage of all the performance, scale, reliability, and security aspects of AWS infrastructure, as well as implement deeper integrations with other AWS-managed services. To learn more, visit https://aws.amazon.com/eks/.
      • GKE: This is a managed K8s service from Google Cloud Platform (GCP) that you can use to deploy and operate containerized applications using Google’s infrastructure. It is available in Standard and Enterprise editions, where the former provides fully automated cluster life cycle management and the latter provides powerful features for governing, managing, and operating containerized workloads at enterprise scale. To learn more, go to https://cloud.google.com/kubernetes-engine.
      • AKS: This is a managed service from Azure that simplifies deploying, managing, and scaling K8s clusters. AKS automates critical tasks such as monitoring, upgrades, and scaling while integrating with other Azure services such as Active Directory, Load Balancer, and Virtual Network. To learn more, go to https://azure.microsoft.com/en-us/products/kubernetes-service.

Apart from these, there are many other managed K8s offerings from companies such as Red Hat, Oracle Cloud Infrastructure (OCI), Alibaba Cloud, and others. The goal of these offerings is to simplify K8s cluster operations and provide deeper integrations with the respective cloud provider infrastructure.

  • Scalability and efficiency: Cloud providers offer seamless scalability for running K8s clusters by providing access to on-demand infrastructure and a pay-as-you-go pricing model. As the clusters grow in size, they automatically scale the K8s control plane components to match their usage.
  • Availability and Global expansion: All managed K8s offerings provide strict uptime service-level agreements (SLAs) – for example, Amazon EKS offers 99.95%. To achieve this, they often deploy multiple instances of an API server with etcd database components spread across multiple Availability Zones (AZs), automatically monitor the health of those components, and recover/replace any unhealthy components. Cloud providers also operate in multiple geographical areas called Regions; note that their definition may vary between cloud providers. For example, an AWS Region consists of multiple physically separated and isolated AZs that are connected with low-latency, high throughput, highly redundant networks. We can utilize these regions to deploy the workload for global users or to implement disaster recovery mechanisms.
  • Security and compliance: There’s always a shared responsibility between cloud providers and consumers. Providers are responsible for the security and compliance of the cloud while you, as a consumer, are responsible for security and compliance in the cloud. This means that the cloud provider ensures the managed components of K8s offerings such as the control plane are secured and meet various compliance standards such as PCI DSS, HIPPA, GDPR, SOC, and others. You, as a consumer, are responsible for securing the applications and self-managed K8s add-ons in the cluster. Additionally, the cloud provider takes care of automatically patching the control plane components to keep them secure.
  • Native integration: To operate a production-ready K8s cluster, we need to integrate with many external components, such as storage systems, databases, load balancers, and monitoring and security tools. Cloud providers often provide managed services for those components and create seamless integrations with their managed K8s offerings. This makes it easier to build end-to-end solutions and takes away the pain of performing compatibility testing for various components. It also provides seamless integrations with various third-party (3P) tools such as Splunk (https://www.splunk.com/), Datadog (https://www.datadoghq.com/), New Relic (https://newrelic.com/), Aqua Security (https://www.aquasec.com/), Sysdig (https://sysdig.com/), Kubecost (https://www.kubecost.com/), and others for monitoring and security purposes, as well as to allocate and optimize the cost of K8s workloads.
  • Extended support: At the time of writing, the K8s community releases a new K8s version approximately three times a year. As depicted in Figure 3*.1*, each version is supported for 12 months. During this time, the community provides patch releases that include bug fixes, security patches, and more. Performing multiple K8s version upgrades often adds significant overhead to the platform engineering teams as each version upgrade involves verifying and remediating any usage of deprecated APIs, as well as upgrading the control plane, data plane, and operational add-ons while ensuring application availability. Cloud providers offer extended support for up to 26 months from the release date so that customers can plan and execute their cluster upgrades. It’s always recommended to stay on the latest K8s releases so that you can leverage the latest innovations from the community, so it’s crucial to automate cluster life cycle operations using Infrastructure as Code (IaC):

Figure 3.1 – K8s release cycle

In this section, we learned about the advantages of using managed K8s offerings from various cloud providers. These let us utilize the seamless scalability of the cloud, ease of management, and global expansion so that we can cater to various geographical customers and meet and exceed security and compliance requirements while operating cost-efficiently. Next, we will set up our first K8s cluster in the AWS cloud using IaC and deploy the my-llama model in it.

Managed K8s offerings are generally upstream and K8s-compliant, which means we can seamlessly migrate the workloads from one offering to another without changing the application code. You may still need to use cloud-provider-specific add-ons to integrate with respective cloud services. Due to this, throughout the rest of this book, we will be using the AWS cloud and Amazon EKS. You can replicate a similar setup using other cloud provider offerings.

Amazon EKS is a regional AWS service that eliminates the need to install, operate, and maintain a K8s control plane on AWS. An Amazon EKS cluster provides a single-tenant, highly available K8s control plane that is spread across three AZs to withstand AZ-wide failures. For the data plane, you can choose from the options shown in Figure 3*.2*:

Figure 3.2 – Amazon EKS data plane options

Let’s learn about these options in detail:

  • Self-managed nodes: This is a group of Amazon EC2 (https://aws.amazon.com/ec2/) instances that are manually managed by the users. Amazon EC2 is a managed service that provides resizable compute capacity in the AWS cloud. Customers are responsible for bootstrapping the worker nodes so that they can join the cluster and managing their life cycle operations (provisioning, updating, and destroying). This option provides fine-grained control over node configuration, setup, and management and also adds operational overhead.
  • EKS-managed node group: This is the most popular choice for EKS users. It provides APIs to automate the process of provisioning and managing the life cycle of the worker nodes. Every managed node group is provisioned as part of an Amazon EC2 Auto Scaling group (ASG) (https://docs.aws.amazon.com/autoscaling/ec2/userguide/auto-scaling-groups.html), which is managed by Amazon EKS. An ASG automatically manages the scaling of EC2 instances, ensuring the appropriate number of instances are running to handle the load. To learn more, go to https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html.
  • AWS Fargate: This is a serverless compute engine for running containerized workloads. With AWS Fargate, you don’t have to manage the underlying compute infrastructure that runs the K8s Pods. AWS handles how the worker nodes are provisioned, configured, patched, and scaled. It automatically provisions the compute capacity that matches your Pod resource requirements and provides higher-level security isolation by providing a dedicated kernel for each Pod. Visit https://docs.aws.amazon.com/eks/latest/userguide/fargate.html to learn more.
  • Karpenter managed nodes: Karpenter is a high-performance cluster autoscaling solution that automatically launches the right amount of compute resources to handle the cluster workloads available. It observes the aggregate resource requirements of unscheduled Pods and makes decisions to launch and terminate the worker nodes. We will explore this in detail in Chapter 6*.* Go to https://karpenter.sh/ to learn more.

For a detailed comparison of these data plane options, you can refer to the EKS documentation at https://docs.aws.amazon.com/eks/latest/userguide/eks-compute.html.

We will be using an IaC tool to automate the process of provisioning the necessary AWS infrastructure. Terraform (https://www.hashicorp.com/products/terraform) is the most popular and cloud-agnostic IaC tool available and is developed by HashiCorp (https://www.hashicorp.com/). It is used to automatically provision and manage resources in any cloud or data center. Terraform uses a domain-specific language called HashiCorp Configuration Language (HCL) (https://github.com/hashicorp/hcl) to define the infrastructure while providing support for input and output variables so that the configuration can be customized. To learn more about Terraform, follow the Get Started - AWS tutorial on the HashiCorp website: https://developer.hashicorp.com/terraform/tutorials/aws-get-started.

To promote modularity, multiple configuration files can be organized into a Terraform module to encapsulate a set of related resources. There is a large Terraform community that maintains the registry of open source modules at https://registry.terraform.io/ that’s available for public use. We will be using the following community modules to provision the necessary infrastructure in this walkthrough:

Let’s start by setting up our environment so that we can provision the EKS cluster using Terraform.

Important note

In this walkthrough, we will be creating AWS resources that are not part of the AWS free tier, so you will incur charges. Please refer to AWS Pricing Calculator at https://calculator.aws/#/ for a cost estimate.

Here are the prerequisites for setting up a K8s cluster in the cloud:

Important note

Terraform providers and modules are frequently updated with new features and fixes. We’ve used the latest compatible versions that were available at the time of writing. You can update those to their latest versions by going to the Terraform Registry at https://registry.terraform.io/.

Let’s start by setting up the Terraform project:

  1. Create a new project directory genai-eks-demo
    $ mkdir -p genai-eks-demo
    $ cd genai-eks-demo
  2. Create a versions.tf file that defines a list of Terraform providers and their respective versions. A Terraform provider is a plugin that interacts with cloud providers, SaaS providers, and other APIs. The AWS Provider (https://registry.terraform.io/providers/hashicorp/aws/latest/docs) enables us to define, provision, and manage AWS resources such as VPCs, EKS clusters, and more. Helm (https://helm.sh/) is a package manager for K8s that allows us to define, install, and upgrade K8s applications using Helm charts. Many community and proprietary pieces of software in the K8s space are distributed via Helm charts, and the Helm provider (https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs) can be used to deploy those software packages in the EKS cluster. Finally, the K8s provider (https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs) is used to interact with the resources in the EKS cluster. You can also download the versions.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/versions.tf:
    terraform {
    required_version = ">= 1.11"
    required_providers {
    aws = {
    source = "hashicorp/aws"
    version = ">= 5.96"
    }
    helm = {
    source = "hashicorp/helm"
    version = ">= 2.17"
    }
    kubernetes = {
    source = "hashicorp/kubernetes"
    version = ">= 2.36"
    }
    }
    }
  3. Create a locals.tf file for storing local variables such as name, AWS Region, and VPC Classless Inter-Domain Routing (CIDR) (https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html) and refer to them our Terraform code. We are also defining a Terraform data source (https://developer.hashicorp.com/terraform/language/data-sources) called azs to fetch the AWS AZs in the given AWS Region (us-west-2) and filtering them by opt-in-status. You can download the locals.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/locals.tf:
    data "aws_availability_zones" "azs" {
    filter {
    name = "opt-in-status"
    values = ["opt-in-not-required"]
    }
    }
    locals {
    name = "eks-demo"
    region = "us-west-2"
    vpc_cidr = "10.0.0.0/16"
    azs = slice (data.aws_availability_zones.azs.names, 0, 3)
    }
  4. Create a providers.tf file for configuring the Terraform providers. Here, we are initializing K8s and Helm providers with the EKS cluster credentials provided to interact with the cluster. You can download the providers.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/providers.tf:
    provider "aws" {
    region = local.region
    }
    provider "kubernetes" {
    host = module.eks.cluster_endpoint
    cluster_ca_certificate = base64decode(module.eks.cluster_certificate_authority_data)
    exec {
    api_version = "client.authentication.k8s.io/v1beta1"
    command = "aws"
    args = ["eks", "get-token", "--cluster-name", module.eks.cluster_name]
    }
    }
    provider "helm" {
    kubernetes {
    host = module.eks.cluster_endpoint
    cluster_ca_certificate = base64decode(module.eks.cluster_certificate_authority_data)
    exec {
    api_version = "client.authentication.k8s.io/v1beta1"
    command = "aws"
    args = ["eks", "get-token", "--cluster-name", module.eks.cluster_name]
    }
    }
    }
  5. Create a vpc.tf file that will define the Amazon VPC, public and private subnets, internet gateway, NAT gateway, and other networking resources required for the EKS cluster. Refer to the AWS documentation at https://docs.aws.amazon.com/vpc/latest/userguide/how-it-works.html to learn more about these concepts. You can download the vpc.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/vpc.tf:
    module "vpc" {
    source = "terraform-aws-modules/vpc/aws"
    version = "~> 5.21"
    name = local.name
    cidr = local.vpc_cidr
    azs = local.azs
    private_subnets = [for k, v in local.azs: cidrsubnet(local.vpc_cidr, 4, k)]
    public_subnets = [for k, v in local.azs: cidrsubnet(local.vpc_cidr, 8, k + 48)]
    enable_nat_gateway = true
    single_nat_gateway = true
    public_subnet_tags = {
    "kubernetes.io/role/elb" = 1
    }
    private_subnet_tags = {
    "kubernetes.io/role/internal-elb" = 1
    "karpenter.sh/discovery" = local.name
    }
    }
    output vpc_id {
    description = "VPC ID"
    value = "${module.vpc.vpc_id}"
    }
  6. To deploy the Amazon VPC resources using Terraform, start by running terraform init (https://developer.hashicorp.com/terraform/cli/commands/init). This command initializes your working directory by downloading the required Terraform provider plugins and configuring the backend for storing Terraform’s state. It ensures that your environment has been set up properly before making any changes. Next, run terraform plan (https://developer.hashicorp.com/terraform/cli/commands/plan) to generate an execution plan, which allows you to preview the actions Terraform will take, such as which resources will be created, modified, or destroyed, without actually making any changes. Reviewing the plan helps catch potential misconfigurations early. Finally, run terraform apply (https://developer.hashicorp.com/terraform/cli/commands/apply) to apply the changes to your infrastructure. This command provisions the defined VPC resources and prompts for confirmation before making any changes:
    $ terraform init
    $ terraform plan
    $ terraform apply -auto-approve
  7. After completion, you will notice the VPC ID in
    Apply complete! Resources: 23 added, 0 changed, 0 destroyed.
    Outputs:
    vpc_id = "vpc-1234567890"
  8. In the eks.tf file, we must define the EKS cluster using the terraform-aws-modules/eks (https://registry.terraform.io/modules/terraform-aws-modules/eks/aws/latest) module. This module simplifies EKS provisioning by abstracting away low-level AWS API calls. Here, we must specify the desired cluster version, VPC subnets, and managed node groups. We are defining one managed node group with a minimum of two EC2 worker nodes from the General Purpose (m) instance family. Feel free to modify the instance_types attribute value if you encounter an InsufficientInstanceCapacity (https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/troubleshooting-launch.html#troubleshooting-launch-capacity) error from AWS. You can choose General Purpose instance types from this page: https://aws.amazon.com/ec2/instance-types/.
  9. In this example, we are defining a managed node group (eks-mng) for an EKS cluster. This node group is a group of EC2 instances that will serve as worker nodes in the cluster. In the instance_types definition for this node group, we are providing choices such as m5.large, m6i.large, m6a.large, and others. EKS will attempt to use one of these instances based on availability. This enables instance-type flexibility, which improves resiliency and may reduce costs by taking advantage of Spot Instance pools or regional availability. You can download the eks.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/eks.tf:
    module "eks" {
    source = "terraform-aws-modules/eks/aws"
    version = "~> 20.36"
    cluster_name = local.name
    cluster_version = "1.32"
    enable_cluster_creator_admin_permissions = true
    cluster_endpoint_public_access = true
    vpc_id = module.vpc.vpc_id
    subnet_ids = module.vpc.private_subnets
    eks_managed_node_groups = {
    eks-mng = {
    instance_types = ["m5.large","m6i.large","m6a.large","m7i.large","m7a.large"]
    max_size = 3
    desired_size = 2
    }
    }
    node_security_group_tags = {
    "karpenter.sh/discovery" = local.name
    }
    }
    output "configure_kubectl" {
    description = "Configure kubectl"
    value = "aws eks --region ${local.region} update-kubeconfig --name ${module.eks.cluster_name}"
    }
  10. Apply the Terraform code to deploy the EKS cluster and the managed node group resources. EKS also deploys default networking add-ons such as vpc-cni, kube-proxy, and CoreDNS in the cluster:
    $ terraform init
    $ terraform plan
    $ terraform apply -auto-approve
    After successful deployment, you will notice the following output. You can use this to configure your kubectl CLI so that it can interact with the EKS cluster:
    Apply complete! Resources: 33 added, 0 changed, 0 destroyed.
    Outputs:
    configure_kubectl = "aws eks --region us-west-2 update-kubeconfig --name eks-demo"
    vpc_id = "vpc-1234567890"
    Copy and run the following command in your terminal to point the kubectl CLI to the eks-demo cluster:
    $ aws eks --region us-west-2 update-kubeconfig --name eks-demo
  11. Next, we will install the required operational add-on software to make our EKS cluster production-ready. This includes add-ons such as AWS Load Balancer Controller (https://kubernetes-sigs.github.io/aws-load-balancer-controller/latest/) to manage the AWS Load Balancer resources for the EKS cluster, Karpenter (https://karpenter.sh/) to manage compute auto-scaling, and more. Download the addons.tf from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/addons.tf. We are using the eks-blueprints-addons (https://github.com/aws-ia/terraform-aws-eks-blueprints-addons) Terraform module to deploy these add-ons on the EKS cluster:
    module "eks_blueprints_addons" {
    source = "aws-ia/eks-blueprints-addons/aws"
    version = "~> 1.21"
    cluster_name = module.eks.cluster_name
    cluster_endpoint = module.eks.cluster_endpoint
    cluster_version = module.eks.cluster_version
    oidc_provider_arn = module.eks.oidc_provider_arn
    enable_aws_load_balancer_controller = true
    ...
    }
    module "karpenter" {
    source = "terraform-aws-modules/eks/aws//modules/karpenter"
    ...
    }
  12. Apply the Terraform code to deploy the add-on software on
    $ terraform init
    $ terraform plan
    $ terraform apply -auto-approve
  13. Verify the installation by running the following kubectl commands. You will notice that there are two worker nodes and 10 K8s Pods running in
    $ kubectl get nodes -o wide
    $ kubectl get pods -A -o wide
  14. This wraps up the initial setup of the EKS cluster. The process is depicted in Figure 3*.3*:

Figure 3.3 – High-level architecture of our EKS cluster

We started by setting up the required tools, which include Terraform, the AWS CLI, kubectl, and others, and created a Terraform project to provision various AWS network components, such as Amazon VPCs, subnets, and internet gateways, before deploying an Amazon EKS cluster alongside AWS Load Balancer and Karpenter add-ons. We will build on top of this setup throughout this book and create a production-ready system for deploying and operating GenAI workloads.

Deploying our first GenAI model in the K8s cluster

Section titled “Deploying our first GenAI model in the K8s cluster”

In this section, we will deploy the Llama model we built in Chapter 2 on the EKS cluster and expose it to our end users using an AWS Network Load Balancer (NLB) (https://aws.amazon.com/elasticloadbalancing/network-load-balancer/). In the K8s world, the smallest unit of deployment is called a Pod (https://kubernetes.io/docs/concepts/workloads/pods/). A Pod consists of one or more containers that share storage and network resources and is defined using a Pod specification. The following is a sample Pod spec for creating a K8s Pod called nginx-pod using the latest nginx container image running on port 80. You can download this manifest file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/nginx-pod.yaml:

apiVersion: v1
kind: Pod
metadata:
name: nginx-pod
spec:
containers:
- name: nginx
image: nginx:latest
ports:
- containerPort: 80

K8s also provides high-level abstracted constructs so that we can manage our workloads declaratively:

Each workload or component of the workload runs as a container inside Pods, and managing these Pods often takes a lot of effort. For example, if a Pod fails, a new replacement Pod needs to be created or a new version of the workload has to be rolled out. These high-level constructs help to abstract these complexities.

Deployment is the most common way to deploy a workload on a K8s cluster. It automates the process of rolling updates, ensuring that new versions of the workload can be released without downtime. We can also apply scaling policies to easily increase or decrease the number of Pods based on demand. Furthermore, deployments use ReplicaSets to ensure high availability by automatically restarting failed Pods and maintaining the desired state of the application, which is critical for resilience in production environments.

In K8s, a Service is an abstraction that enables you to expose one or more Pods over a network. It defines a logical group of endpoints, typically consisting of Pods, and includes a policy that governs their accessibility. There are many different types of K8s Service objects:

In this walkthrough, we will be exposing our application using the LoadBalancer Service type, which, in turn, will provision our NLB in the AWS cloud.

Let’s create a deployment specification for the my-llama container we created in Chapter 2. To do this, we need to upload the local container image to a container registry so that it can be downloaded by EKS. Amazon Elastic Container Registry (Amazon ECR) (https://aws.amazon.com/ecr/) is a fully managed container registry service for storing, sharing, and deploying container software anywhere. Create a file named ecr.tf that contains the following Terraform code to create an Amazon ECR repository and enable image tag immutability to prevent image tags from being overwritten. You can download the ecr.tf file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/ecr.tf:

resource "aws_ecr_repository" "my-llama" {
name = "my-llama"
image_tag_mutability = "MUTABLE"
}
output "ecr_push_cmds" {
description = "Command to authenticate with ECR and push the container image."
value = <<EOT
aws ecr get-login-password --region ${local.region} | docker login --username AWS --password-stdin ${aws_ecr_repository.my-llama.repository_url}
docker tag my-llama ${aws_ecr_repository.my-llama.repository_url}
docker push ${aws_ecr_repository.my-llama.repository_url}
EOT
}

Run the following commands to create the ECR repository:

$ terraform plan
$ terraform apply -auto-approve

Run the terraform output command to list the ECR upload commands. Copy and paste those output commands in your terminal to push the my-llama container image to the ECR repository:

$ terraform output -raw ecr_push_cmds
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama
docker tag my-llama 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama
docker push 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama

Create the K8s deployment resource using the my-llama ECR image:

$ kubectl create deploy my-llama --image 123456789012.dkr.ecr.us-west-2.amazonaws.com/my-llama
deployment.apps/my-llama created

It may take a couple of minutes for the K8s deployment to get into the Ready state. You can verify this by running the following command and looking for the Ready status:

$ kubectl get deploy my-llama
NAME READY UP-TO-DATE AVAILABLE AGE
my-llama 1/1 1 1 6m

Now that the my-llama model is being deployed to the EKS cluster, the next step is to expose it outside the cluster using an AWS NLB. We will be using the aws-load-balancer-controller add-on that was installed as part of our EKS cluster setup to provision the NLB. Create a file called my-llama-svc.yaml that contains the following content. This will create a K8s service of the LoadBalancer type on port 80 and forward the traffic to port 5000 on the my-llama container. Here, we’re also adding annotations to make it an internet-facing NLB.

You can download the my-llama-svc.yaml file from our GitHub repository at https://github.com/PacktPublishing/Kubernetes-for-Generative-AI-Solutions/blob/main/ch3/my-llama-svc.yaml:

Important note

We are creating a public-facing NLB for testing purposes. Feel free to restrict access to your IP address by updating the inbound rules of the NLB security group. Please refer to the AWS NLB documentation at https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-security-groups.html for more details.

apiVersion: v1
kind: Service
metadata:
labels:
app: my-llama-svc
name: my-llama-svc
annotations:
service.beta.kubernetes.io/aws-load-balancer-type: "external"
service.beta.kubernetes.io/aws-load-balancer-scheme: "internet-facing"
spec:
ports:
- port: 80
protocol: TCP
targetPort: 5000
type: LoadBalancer
selector:
app: my-llama

Deploy the K8s service and fetch the NLB hostname by running the following commands:

$ kubectl apply -f my-llama-svc.yaml
service/my-llama-svc created
$ export NLB_URL=$(kubectl get svc my-llama-svc -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
$ echo $NLB_URL

It may take up to 5 minutes for the K8s Pod endpoints to be registered to the AWS NLB and become healthy. You can run the following commands to look at the K8s Pod logs, events, and service status:

$ kubectl describe pod -l app=my-llama
$ kubectl logs -f -l app=my-llama
$ kubectl describe svc my-llama-svc

Now, we can invoke the Llama model by using this NLB endpoint. Run the following curl command to send a test prompt to the my-llama service. It will generate a response by forwarding the prompt to the Llama model:

$ curl -X POST http://$NLB_URL/predict -H "Content-Type: application/json" -d '{"prompt":"Create a poem about humanity?","sys_msg":"You are a helpful, respectful, and honest assistant. Always provide safe, unbiased, and positive responses. Avoid harmful, unethical, or illegal content. If a question is unclear or incorrect, explain why. If unsure, do not provide false information."}' | jq .

In this section, we deployed our my-llama container image as a K8s deployment in an EKS cluster and exposed it to the internet using an AWS NLB by creating the K8s LoadBalancer Service. Finally, we ran inference on our LLM by using the curl utility against the AWS NLB endpoint’s URL. Similarly, you can containerize other publicly available models such as Mistral (https://huggingface.co/mistralai), Falcon (https://huggingface.co/tiiuae), and DeepSeek (https://huggingface.co/deepseek-ai) and deploy them in your EKS cluster.

In this chapter, we discussed how cloud computing has fundamentally changed how we access and utilize compute resources, offering scalability, accessibility, and cost-efficiency through pay-as-you-go models. Managed K8s services provided by major cloud providers simplify the deployment and management of K8s clusters, which is particularly beneficial for running GenAI models. We used Amazon EKS, a managed, upstream K8s-compliant service as an example and covered how to automate the process of setting up an EKS cluster. Then, we utilized Terraform for cluster provisioning, set up a Terraform project with the required providers, and used community modules to create AWS resources such as VPCs, EKS clusters, EKS-managed node groups, and cluster add-ons. After, we deployed our my-llama model as a K8s deployment on the EKS cluster and exposed it to the internet using the K8s LoadBalancer Service.

In the next chapter, we will discuss techniques for optimizing a general-purpose foundational model for domain-specific use cases, such as chatbots. We will cover some specific techniques such as Retrieval-Augmented Generation (RAG) and fine-tuning methods while providing an in-depth exploration of how to implement them.

Get This Book's PDF Version and Exclusive Extras

Join the CloudPro Newsletter with 44000+ Subscribers

Want to know what’s happening in cloud computing, DevOps, IT administration, networking, and more?