Showing posts with label pod. Show all posts
Showing posts with label pod. Show all posts

How to Expose a Kubernetes Pod to a Specific Port for Running an application

If you are running an application on Kubernetes, you may want to expose a specific port to a pod so that you can access it outside world. Kubernetes provides several ways to do this and we are going to use one of the method.

Step 1: Let's create an HTML application 

I am going to create an EMI calculator using HTML and Javascript and save it as index.html

<!DOCTYPE html>
<html>
<head>
<title>EMI Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
form {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 50px;
}
input[type="number"], select {
padding: 10px;
margin-bottom: 20px;
width: 300px;
border-radius: 5px;
border: none;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
input[type="submit"] {
padding: 10px;
width: 200px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #3e8e41;
}
</style>
</head>
<body>
<h1>EMI Calculator</h1>
<form onsubmit="calculateEMI(); return false;">
<label for="principal">Loan Amount:</label>
<input type="number" id="principal" name="principal"
placeholder="Enter loan amount in INR" required>

<label for="interest">Interest Rate:</label>
<input type="number" id="interest" name="interest"
placeholder="Enter interest rate in %" required>

<label for="tenure">Loan Tenure:</label>
<select id="tenure" name="tenure" required>
<option value="">--Select Loan Tenure--</option>
<option value="12">1 Year</option>
<option value="24">2 Years</option>
<option value="36">3 Years</option>
<option value="48">4 Years</option>
<option value="60">5 Years</option>
</select>

<input type="submit" value="Calculate EMI">
</form>

<div id="result"></div>

<script>
function calculateEMI() {
// Get input values
let principal = document.getElementById('principal').value;
let interest = document.getElementById('interest').value;
let tenure = document.getElementById('tenure').value;

// Calculate EMI
let monthlyInterest = interest / 1200; // 12 months * 100%
let monthlyPayment =
(principal * monthlyInterest) / (1 - (1 / Math.pow(1 + monthlyInterest, tenure)
));
let totalPayment = monthlyPayment * tenure;

// Display result
document.getElementById('result').innerHTML = `
<h2>EMI Calculation Result</h2>
<p>Loan Amount: INR ${principal}</p>
<p>Interest Rate: ${interest}%</p>
<p>Loan Tenure: ${tenure} months</p>
<p>Monthly EMI: INR ${monthlyPayment.toFixed(2)}</p>
<p>Total Payment: INR ${totalPayment.toFixed(2)}</p>
`;
}
</script>
</body>
</html>

Now your html application is ready. 

Step 2: Dockerize your application

let's create a Dockerfile with below command inside it and name it Dockerfile in the same location.

FROM nginx:alpine
COPY index.html /usr/share/nginx/html/index.html

Here we are using nginx server where our index file/EMI calculator will be hosted.

Step 3: Build an image for your application

Use below command to build an image

docker build -t emi .

here -t is called as tag and emi is tag name.

. is current directory. So the docker build command will look for Dockerfile in current directory.

=> [internal] load build definition from Dockerfile
=> => transferring dockerfile: 201B
=> [internal] load .dockerignore
=> => transferring context: 2B
=> [internal] load metadata for docker.io/library/nginx:alpine
=> [internal] load build context
=> => transferring context: 79B
=> [1/2] FROM docker.io/library/nginx:alpine
=> CACHED [2/2] COPY index.html /usr/share/nginx/html/index.html

You would see output like this above.

Now if you check if the image has been created with below command.

docker images

You would see the tag name as emi in your result.

Step 4: Create a deployment

Since we have already created an image, now it's time to create a deployment using the same image.

apiVersion: v1
kind: Pod
metadata:
name: emi
namespace: default
spec:
containers:
- name: emi
image: emi:latest
imagePullPolicy: Never
restartPolicy: Never

save it as deployment.yaml

Now run the below command to create a deployment:

kubectl apply -f deployment.yaml

Once command is completed. Let's verify it by kubectl get pod command like below.

kubectl get pods
NAME READY STATUS RESTARTS AGE
emi 1/1 Running 0 7s

Step 5: Access it via browser

Since we have already created our application want to access it via browser. We may need to use port forwarder. It is for TCP connections only.

kubectl port-forward emi 8087:80

Once command has been completed. Let's access it via localhost:8087 in the browser.


Finally we have created an application, dockerized it and running it on a Pod and able to access via browser. That was it about the spinning up an application on Pod.

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

Know about Kubernetes Security

 Introduction




Kubernetes has become the most popular container orchestration tool, enabling organizations to deploy and manage containerized applications at scale. However, this popularity has also made it an attractive target for cybercriminals. Kubernetes security is critical to safeguarding your containerized applications and data. In this article, we will discuss the risks involved in Kubernetes security and how to harden pod security with code.

Risk


Kubernetes security risks come from different areas, including:

  • Container images: Container images used to create pods may contain vulnerabilities that can be exploited by attackers.

  • API server: The Kubernetes API server is a central point of control for managing Kubernetes clusters. An attacker who gains access to the API server can control the entire cluster.

  • Network security: Kubernetes allows pods to communicate with each other and the outside world. Without proper network security, an attacker can intercept network traffic or launch a denial-of-service attack.

  • Authorization and access control: Access to Kubernetes resources should be restricted based on the principle of least privilege. If authorization and access control are not properly implemented, an attacker can gain access to sensitive data and resources.


Hardening Pod security with code


Hardening pod security involves implementing security best practices at the code level. Here are some tips for hardening pod security:

  • Use least privilege: Grant the minimum level of privileges necessary for pods to function. Use role-based access control (RBAC) to enforce these privileges.

  • Use security contexts: Kubernetes security contexts allow you to set security policies for pods. You can use security contexts to specify a range of settings, such as user IDs, file permissions, and capabilities.

  • Use container image scanning: Use tools such as Aqua Security, Anchore, or Trivy to scan container images for vulnerabilities before deploying them in Kubernetes.

  • Use network policies: Use network policies to restrict pod-to-pod communication and ingress/egress traffic.

  • Implement secure service accounts: Kubernetes service accounts provide authentication tokens for pods to access the Kubernetes API server. Use RBAC to restrict the permissions of service accounts.

  • Monitor Kubernetes API server activity: Monitor Kubernetes API server activity for any suspicious activity or unauthorized access.

  • Here's an example of how to harden pod security by using security contexts and network policies in Kubernetes YAML configuration file:

  • apiVersion: v1
    kind: Pod
    metadata:
    name: my-pod
    spec:
    containers:
    - name: my-container
    image: my-image
    securityContext:
    runAsUser: 1000
    capabilities:
    add:
    - NET_ADMIN
    ports:
    - containerPort: 80
    securityContext:
    runAsUser: 1000
    networkPolicy:
    ingress:
    - from:
    - podSelector:
    matchLabels:
    app: my-app


In this example, we have defined a pod named "my-pod" that includes a container named "my- container" and a security context that specifies the user ID and capabilities of the container. We have also defined a network policy that restricts incoming traffic to the pod only from pods labeled with "app: my-app".

The "securityContext" section of the YAML file specifies the following settings:

"runAsUser": The container runs as user ID 1000, which is a non-root user. This reduces the risk of privilege escalation attacks.
"capabilities": The container has added the "NET_ADMIN" capability, which allows it to perform network administration tasks. By limiting the container's capabilities, we reduce the risk of a container being used to launch an attack.

The "networkPolicy" section of the YAML file specifies the following settings:

"ingress": This network policy restricts incoming traffic to the pod only from pods labeled with "app: my-app". This helps prevent unauthorized access to the pod.

By using security contexts and network policies in this way, we can help harden pod security and reduce the risk of a Kubernetes security breach.


Conclusion


Kubernetes security is critical for protecting your containerized applications and data. The risks involved in Kubernetes security come from different areas, including container images, API server, network security, and authorization and access control. To harden pod security, implement security best practices at the code level, including using least privilege, security contexts, container image scanning, network policies, secure service accounts, and monitoring Kubernetes API server activity. By following these best practices, you can minimize the risk of a Kubernetes security breach and ensure the security of your containerized applications.


Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

How to delete a Pod in Kubernetes - Beginner tutorial

Delete a pod using kubectl delete pod





Sometimes we encounter some issues on running pod and then we decide to delete a Pod because we can't create a new pod with the same name. You can't have two pods with same name in a cluster. 

There are two ways to delete a pod: 
  • Using delete command
  • Using delete command with force keyword
The first way of deleting the pod is called a graceful delete. So before deleting any pod we first need to create a new pod.

Create a pod

To create a pod we need to run below command in our terminal.

kubectl run nginx --image=nginx --restart=Never


Above command will run nginx image with pod name nginx itself. 
Here --restart flag says kubernetes to create a single pod not to create a deployment.

Now check if the pod is running using below command

kubectl get pod


Output:

NAME    READY   STATUS              RESTARTS   AGE

nginx   0/1     ContainerCreating   0          8s


Just wait for few seconds and pod will be created.

kubectl get pod

NAME    READY   STATUS    RESTARTS   AGE

nginx   1/1     Running   0          2m6s


Since we have created our pod. Now lets try to delete it. To delete a pod you can use below command.

kubectl delete pods nginx


Here in the syntax you need to pass pod name that's it. In this case I passed nginx.

This may take some time depending upon pod usage. But if you want this to be deleted quickly then we can use force flag in the command.

A pod is not deleted automatically when a node is unreachable.The pods running on an unreachable Node enter the terminating or unknown state after timeout. Pods may also enter these states when user attempts graceful deletion of pod on unreachable node. The only ways in which a pod can be deleted/removed from apiserver are as follows:
  • The node object is deleted.
  • The kubelet on unresponsive node starts responding ,kills the pod and removes the pod from apiserver.
  • Force deletion of pod by user.
The recommended best practice is to follow first two from above. If a node is confirmed to be dead then
delete the node object. Normally system deletes the pod once it's no longer running on a node or the node is deleted by administrator. 

Delete the pod forcefully using below command:

kubectl delete pod nginx --force 

Output:

pod "nginx" force deleted


If even after above command the pod is still stuck on unknown state. You can use the below command to remove the pod from the cluster.

kubectl patch pod nginx -p '{"metadata":{"finalizers":null}}'


That was it about deleting the pod using kubectl command. Be careful while deleting a pod especially using the force keyword.

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

How to search image name in multiple Pods on Kubernetes like a Pro?



Introduction

Sometimes we have a requirement to find a particular image which any pod is using. But you are not sure about the image. In that case we have the describe command to check and see all the information about the pod. The problem occurs when you have multiple pods and you can't write multiple describe commands to find that image. So we'll do it differently using a loop like Pro. 

Prerequisites

You need to have the Kubernetes installed on your machine and it's up and running. You can check it by running below command.

kubectl get pods

If you see some error like command not found then probably you don't have Kubernetes installed on your machine so you need to get it installed. 

Let's start

First we'll create multiple Pods on our cluster with different images. Code is below:

for img in nginx3 alpine alpine2 alpine3
do
kubectl run $img --image=$img
done


Results:
pod/nginx3 created
pod/alpine created
pod/alpine2 created
pod/alpine3 created

So I used a for loop in bash script and passed multiple images name and created multiple Pods at once.

Now I am checking the status of pods. Since i used wrong images so there must be multiple pods in not running status.

kubectl get pods

NAME READY STATUS RESTARTS AGE
alpine 0/1 CrashLoopBackOff 4 (56s ago) 3m10s
alpine2 0/1 ImagePullBackOff 0 3m10s
alpine3 0/1 ImagePullBackOff 0 3m10s
nginx 1/1 Running 0 3h38m
nginx2 1/1 Running 0 3h33m
nginx3 0/1 ImagePullBackOff 0 3m10s

So we have multiple Pods now, we can look for images using our favourite for loop.

Let's list Pod and it's image.

for pds in $(kubectl get pods --no-headers -o custom-columns=":metadata.name")
do
echo "*************Pod_Name: $pds**************"
kubectl describe pods $pds | grep -i image:
done

Results:

********************Pod_Name: alpine***************
Image: alpine
********************Pod_Name: alpine2**************
Image: alpine2
********************Pod_Name: alpine3**************
Image: alpine3
*******************Pod_Name: nginx*****************
Image: nginx
*******************Pod_Name: nginx2****************
Image: nginx
*******************Pod_Name: nginx3****************
Image: nginx3

Now we can see which Pod is using which image. But this solution is still not feasible because this will give me all the pods and images in default namespace. I need to search one image ie. alpine3 among all Pods.

for pds in $(kubectl get pods --no-headers -o custom-columns=":metadata.name")
do
echo "************Pod_Name: $pds**************"
kubectl describe pods $pds | grep -i "image: alpine3"
done


Just search alpine3 in your grep command and see results below. You can use if else to remove extra print from the output.

for pds in $(kubectl get pods --no-headers -o custom-columns=":metadata.name")
do
if kubectl describe pods $pds | grep -q -i "image: alpine3"
then
echo "***********Pod_Name: $pds*****************"
else
echo
fi
done

*************Pod_Name: alpine3**************

Conclusion

Combining your shell scripting skill can be very useful in Kubernetes. You can get multiple things done quickly. This was example to find images in multiple Pods but you can use above script to find other properties as well like variables and configs. Using shell script you can automate lot of stuff on Kubernetes. 


Default memory limits for a Kubernetes Pod

Understanding about memory and other resources consumption is very important in Kubernetes. Whenever we run a Pod it consumes some amount of memory and cpu depending on the load.

By default Pods run with unbounded CPU and memory limits. That means any Pod in the system will be able to consume as much CPU and memory on the node that executes the Pod. So to avoid these situations user can impose some restrictions on the amount of resource a single Pod can use for variety of reasons. 

To impose a memory restrictions we have few options:

1. Either we can define our memory and cpu limits in deployment file

2. Or we can create a limit which will used to set default memory limit to Pods in specific namespace.

Let's create a namespace first by below command.

kubectl create namespace memory-demo

Now create a pod using yaml file.

apiVersion: v1
kind: Pod
metadata:
name: mem-demo
namespace: memory-demo
spec:
containers:
- name: mem-demo-cont
image: polinux/stress
resources:
requests:
memory: "100Mi"
limits:
memory: "200Mi"
command: ["stress"]
args: ["--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"]

We have provided a memory limit 200Mi. Save it as mempod.yaml and run below command to create the pod.

kubectl create -f mempod.yaml

Note: Mi and MB are different but they are close in size. 
Mi(Mebibyte) = 1024 KB
MB(Megabyte) = 1000 KB

Now let's check the memory consumption of above pod using below command.

kubectl get pod mem-demo -n memory-demo -o yaml | grep -i resources -A 4

O/P:

resources:
limits:
memory: 200Mi
requests:
memory: 100Mi

Let's try to understand what will happen when pod will exceed the memory limit. We'll create a pod again to exceed memory limits. Use the above mempod.yaml file and just change the memory limits to lower and see.

apiVersion: v1
kind: Pod
metadata:
name: mem-demo
namespace: memory-demo
spec:
containers:
- name: mem-demo-cont
image: polinux/stress
resources:
requests:
memory: "50Mi"
limits:
memory: "50Mi"
command: ["stress"]
args: ["--vm", "1", "--vm-bytes", "150M", "--vm-hang", "1"]

Before creating the same again again we need to delete the existing pod first using below command.

kubectl delete pod mem-demo -n memory-demo

kubectl create -f mempod.yaml


Check if new pod created is in running state? by running below command

kubectl get pods -n memory-demo

NAME READY STATUS RESTARTS AGE
mem-demo 0/1 CrashLoopBackOff 6 9m34s

So it's not running and it's failed. Let's debug why it's failed using kubectl describe command.

kubectl describe pods mem-demo -n memory-demo | grep -i state -A 5
State: Waiting
Reason: CrashLoopBackOff
Last State: Terminated
Reason: OOMKilled
Exit Code: 1

It says OOM killed means memory limit was exceeded and it was killed. 

Instead of assigning memory limits and resources to individual pods we can create memory limits in namespace and every pod created in this namespace will have the default memory limit. 

To do this we'll create a limit range in memory-demo namespace. 

apiVersion: v1
kind: LimitRange
metadata:
name: mem-limit-range
spec:
limits:
- default:
memory: 512Mi
defaultRequest:
memory: 256Mi
type: Container

save it as limit.yaml

kubectl apply -f limit.yaml -n memory-demo

So limit range has been created and we can verify it by below command.

kubectl get limits -n memory-demo

NAME CREATED AT
mem-limit-range 2022-08-07T13:27:36Z

Now create a Pod using imperative command way

kubectl run nginx --image=nginx -n memory-demo

And check the memory limits for the container , it should be default limits by limit range.

spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
resources:
limits:
memory: 512Mi
requests:
memory: 256Mi

That's how we can use the limit range to set default memory limits.

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

Creating a Pod inside a Namespace

 Creating a Pod inside a Namespace




We are going to understand what is namespace in programming and what is namespace in Kubernetes world. Both are actually very much same. So today we'll talk about the namespace ,how to create it, check it and creating a Pod in a namespace.

Namespace

A namespace is set of signs or names that are used to identify and refer to objects of various kinds. A namespace ensures that all of the objects have unique name so that they can be easily identified. You can 
correlate this with schema in SQL server database where you can have multiple  tables with same name but in different schema. 

Similarly you can have multiple pods with same name but in different namespace.

How to check all available namespaces?

You can run kubectl get namespaces to get all available namespaces on cluster.

kubectl get namespaces

NAME              STATUS   AGE

default           Active   2d

kube-public       Active   2d

kube-system       Active   2d


You can also run kubectl get ns , where ns is short form of namespace.

How to create a namespace

To create a namespace you need to run kubectl create namespace namespace_name

kubectl create namespace test

namespace/test created


kubectl get namespaces         

NAME              STATUS   AGE

default           Active   82d

kube-public       Active   82d

kube-system       Active   82d

test              Active   5s


You can see test namespace has been created. 

Now you'll notice what are these namespaces other than test. I didn't create them. Let me explain.

  • kube-system: Namespace for objects created by kubernetes system
  • default: It's default namespace when you don't specify name then objects will be created in default namespace
  • kube-public: This is created automatically and readable by all users. This namespace is mostly reserved for cluster usage.

Let' create a Pod in test namespace now using below commands.

kubectl run mypod --image=nginx -n test

kubectl run mypod --image=nginx -n test

pod/mypod created


Let's check the pod and make sure you look at test namespace.

kubectl get pods -n test

NAME    READY   STATUS    RESTARTS   AGE

mypod   1/1     Running   0          2m10s


I have created mypod in prod namespace as well. So we can have an application with same name but in different namespace.

kubectl run mypod --image=nginx -n prod

pod/mypod created


kubectl get pods -n prod               

NAME    READY   STATUS    RESTARTS   AGE

mypod   1/1     Running   0          14s



Conclusion

Namespace is very useful when deploying your application on cluster. It's always a best practice to create a namespace and deploy your application. You can think of a scenario where one team creates a pod with name testPod and other team also tries to name a pod testPod. So in this case Pod creation will be failed due to duplicate name. So best practice says create your pod inside a namespace. 

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

Debugging your pod on Kubernetes?

 Debugging the pods on Kubernetes




Debugging is very important to identify the issue in Pod. sometimes your application may behave differently /wrong. Your Pod has stopped or some other issues happening inside your Pod. You can always debug that to identify the issue and fix it. 

So the most basic thing we do to debug the issue is to start with checking the logs. Logs are very crucial part and play very important role in any application. If anything goes wrong we can always check the logs and analyse it. Similar to above we are going to check the logs, events and definition of Pod to identify the issues. 

To start with it, we first need to run the pod. You can follow below command to run the pod.


kubectl run mypod --image=nginx


Here mypod is name of the pod and nginx image will be used.

Check if the pod is running. 

kubectl get pods


Result below:

NAME    READY   STATUS              RESTARTS   AGE

mypod   0/1     ContainerCreating   0          5s


It says container creating state. We may wait and see if it is completed and running state.

NAME    READY   STATUS    RESTARTS   AGE

mypod   1/1     Running   0          21s


So it's in running state. We can also use yaml file to create the pod.

Let's break something and see what we issues and status we get. I'll delete the pod and recreate it with the wrong image name.

To delete the Pod use below command:


kubectl delete pod mypod

pod "mypod" deleted


Now since the pod has been delete let's recreate it with wrong image.

kubectl run mypod --image=nginx-myimage-123


Run it and pod will be created successfully. But wait did we check the status if the pod is running. 
Check it using Kubectl get pods command.

kubectl get pods

NAME    READY   STATUS         RESTARTS   AGE

mypod   0/1     ErrImagePull   0          9s


You can identify under the status column that there is an error. It says ErrImagePull. We can guess that there is an error during image pull. We know that because we put that wrong image name. But in real life scenario we don't know about if our image is wrong. So we can check the events. 

To check the events we can use describe command:

kubectl describe pod mypod


Once we run this command it will give us result in key/value pair format. Just scroll to the bottom and look for the events. 

Events:

  Type     Reason     Age                From               Message

  ----     ------     ----               ----               -------

  Normal   Scheduled  34s                default-scheduler  Successfully assigned default/mypod to docker-desktop

  Normal   BackOff    26s                kubelet            Back-off pulling image "nginx-myimage-123"

  Warning  Failed     26s                kubelet            Error: ImagePullBackOff

  Normal   Pulling    12s (x2 over 33s)  kubelet            Pulling image "nginx-myimage-123"

  Warning  Failed     6s (x2 over 27s)   kubelet            Failed to pull image "nginx-myimage-123": rpc error: code = Unknown desc = Error response from daemon: pull access denied for nginx-myimage-123, repository does not exist or may require 'docker login': denied: requested access to the resource is denied

  Warning  Failed     6s (x2 over 27s)   kubelet            Error: ErrImagePull


Here we can see it says either repository does not exist or we don't have access to it. 

So checking the events is very important step. This can tell us what happened when we ran our kubectl run command. There is one more way by which we can check and that is logs. By checking logs can give us some insights. Sometimes we don't get much information from the events and in those scenarios checking logs can be very helpful if we can find something. We can check the log in this case as well but since the issue is only with image. We used wrong image name and this issue was very much understandable from the events. But let's check the logs anyway by running below command.

kubectl logs mypod


Result:

Error from server (BadRequest): container "mypod" in pod "mypod" is waiting to start: trying and failing to pull image


In logs also we can check that its saying "trying and failing to pull image" step.

If we have specific container failing inside the pod then you can run below command.

kubectl logs mypod container_name                           

If our container has ever crashed previously then we can use --previous flag in command.

kubectl logs --previous mypod container_name                 

Conclusion 

These are the basic ways by which we can check and fix the issues in Pod. Events can be very helpful but sometimes logs can be more helpful. So it depends on what is the issue. It's always better to check for events and then go for logs. 

Hope this can be helpful!

Note: If you think this helped you and you want to learn more stuff on devops, then I would recommend joining the Kodecloud devops course and go for the complete certification path by clicking this link

Quantum Computing: The Future of Supercomputing Explained

  Introduction Quantum computing is revolutionizing the way we solve complex problems that classical computers struggle with. Unlike tradi...