<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Rabie on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Rabie on Medium]]></description>
        <link>https://medium.com/@mohamed180235?source=rss-873c55cee36d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yuRj8fuR7z0dAwOeB0Rdmg.jpeg</url>
            <title>Stories by Mohamed Rabie on Medium</title>
            <link>https://medium.com/@mohamed180235?source=rss-873c55cee36d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:24:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed180235/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Kubernetes RBAC: A Comprehensive Guide]]></title>
            <link>https://medium.com/@mohamed180235/mastering-kubernetes-rbac-a-comprehensive-guide-9dc0eb40bda9?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dc0eb40bda9</guid>
            <category><![CDATA[rbac-access-control]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 13:08:53 GMT</pubDate>
            <atom:updated>2025-08-16T13:08:53.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZbIy4O6S7eEEC5tYYEG2ZQ.png" /></figure><p>If you start studying or working as a DevOps Engineer, you will always hear about a critical concept in Security, which is the “least privilege”. This concept provides users with only the necessary permissions. This is precisely where Role-Based Access Control (RBAC) comes into play.</p><p>In this comprehensive guide, we’ll dive deep into Kubernetes RBAC, covering its core concepts. Starting from authorization modes available in Kubernetes, with a particular focus on RBAC, and providing practical examples for configuring and managing access within your cluster.</p><h4>What are Kubernetes Authorization Modes?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*NQ2xeB3EVmLepdAUm8MafQ.png" /></figure><p>Before we jump into RBAC, it’s essential to understand the different authorization modes Kubernetes offers. An authorization mode determines whether a request (e.g., kubectl get pods) is allowed or denied.</p><p>The Kubernetes API server supports several authorization modes, which are evaluated sequentially. If any authorizer approves or denies a request, that decision is immediately returned. If all modules have no opinion, the request is denied.</p><p>The — authorization-mode flag is used to configure these modes when starting the API server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*1WO0pU7VKHcGL2WffUcVVA.png" /></figure><p>Let’s explore the primary authorization modes:</p><h3>AlwaysAllow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0HRYH1FrLxOLGuGWI9gqoQ.png" /></figure><p>As the name suggests, the<strong><em>AlwaysAllow</em></strong> mode allows all requests. It’s primarily used for testing or development clusters where security is not a concern. Never use this in production!</p><p>It bypasses all authorization checks, meaning any authenticated user can perform any action on any resource. It is strongly advised against using this mode in any untrusted environment or where the API server is exposed to the public internet.</p><h3>AlwaysDeny</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UFgdpGg_9zKVtrAeX9E81Q.png" /></figure><p>Conversely, the<strong><em>AlwaysDeny</em></strong> mode blocks all requests. This mode is primarily used for testing purposes, ensuring that no requests are authorized. It effectively locks down the cluster, making it inaccessible.</p><h3>ABAC (Attribute-Based Access Control)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*x5ae-UrQ3NTXQPGnEyIhCQ.png" /></figure><p><strong>ABAC</strong> is an authorization mode where access rights are granted based on attributes associated with the user, resource, or environment.</p><p>In Kubernetes, ABAC policies are defined in a policy file that the API server reads at startup. While powerful and flexible, managing ABAC policies can become complex and cumbersome in large environments, as policies are static and require a restart of the API server to apply changes. Due to its complexity and static nature, ABAC has largely been superseded by <strong>RBAC</strong> as the preferred authorization method in Kubernetes.</p><h3>Node Authorization</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*DPJ92fktprPL3Ut6B7necg.png" /></figure><p><strong>Node authorization</strong> is a special-purpose authorization mode designed to grant permissions to <strong>kubelets</strong> (the agent that runs on each node in the cluster) based on the pods they are scheduled to run.</p><p>This mode ensures that a kubelet can only access resources (like pods, events, and nodes) that are relevant to its assigned responsibilities. It prevents a compromised kubelet from gaining unauthorized access to other parts of the cluster. <strong>This mode is typically used in conjunction with RBAC.</strong></p><h3>RBAC (Role-Based Access Control)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*3Cr2svNzLuRYvF23" /></figure><p><strong>RBAC </strong>is the recommended and most widely adopted authorization mode in Kubernetes for production clusters. It enables administrators to dynamically configure permission policies through the Kubernetes API, providing fine-grained control over who can perform what actions in the cluster.</p><h3>Configuring Authorization Modes &amp; Multiple Authorization Modes</h3><p>To configure authorization modes, you start the Kubernetes API server with the<em>--authorization-mode</em> flag, specifying a comma-separated list of modes. The order of the modes matters, as they are evaluated sequentially. For example:</p><pre>kube-apiserver --authorization-mode=Node,RBAC</pre><p>In this example, the<strong>Node</strong> authorizer is checked first, followed by<strong>RBAC</strong>. If <strong>Node</strong>approves or denies the request, the decision is final. If <strong>Node</strong> has no opinion, <strong>RBAC</strong>is then consulted. If all configured authorizers have no opinion, the request is denied.</p><p>It’s common practice to use multiple authorization modes in production environments, typically <strong>Node</strong> and <strong>RBAC</strong>, to leverage the strengths of each. <strong>Node</strong> authorization provides essential security for kubelets, while <strong>RBAC</strong> offers granular control over user and service account permissions.</p><h3>RBAC: The Core of Kubernetes Access Control</h3><p><strong>RBAC</strong> allows you to define granular permissions and assign them to users or service accounts. It is based on four key Kubernetes API objects:</p><ul><li><strong>Role:</strong> A Role defines a set of permissions within a specific namespace. It specifies what actions (verbs like get, list, create, delete) can be performed on what resources (like pods, deployments, services).</li><li><strong>RoleBinding:</strong> A RoleBinding grants the permissions defined in a <strong>Role </strong>to a <strong>user, group, or service account</strong> within a specific namespace. <strong><em>It links a Role to a set of subjects (users, groups, or service accounts).</em></strong></li><li><strong>ClusterRole:</strong> Similar to a Role, but a <strong>ClusterRole </strong>defines permissions across the entire <strong>cluster</strong>, not limited to a single namespace. This is used for granting access to cluster-scoped resources (like nodes, persistentvolumes) or for granting the same permissions to resources across all namespaces.</li><li><strong>ClusterRoleBinding: </strong>A <strong>ClusterRoleBinding </strong>grants the permissions defined in a <strong>ClusterRole </strong>to a <strong>user, group, or service account</strong> across the entire cluster. <strong><em>It links a ClusterRole to a set of subjects at the cluster level.</em></strong></li></ul><h3>How to create Role and RoleBinding &amp; Example</h3><p>Roles are namespace-scoped, meaning they grant permissions only within a particular namespace. RoleBindings then bind these Roles to subjects.</p><h3>Creating a Role</h3><p>Let’s create a Role named pod-readerin the defaultnamespace that allows reading (get, watch, list) pods.</p><pre># pod-reader-role.yaml<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: default<br>  name: pod-reader<br>rules:<br>- apiGroups: [&quot;&quot;] # &quot;&quot; indicates the core API group<br>  resources: [&quot;pods&quot;]<br>  verbs: [&quot;get&quot;, &quot;watch&quot;, &quot;list&quot;]</pre><p>To create this Role, save the above content as pod-reader-role.yaml and run:</p><pre>kubectl apply -f pod-reader-role.yaml</pre><h3>Creating a RoleBinding</h3><p>Now, let’s create a RoleBinding named read-pods-binding in the default namespace that binds the pod-reader Role to a user named dev-user.</p><pre># read-pods-binding.yaml<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: read-pods-binding<br>  namespace: default<br>subjects:<br>- kind: User<br>  name: dev-user # Name is case sensitive<br>  apiGroup: rbac.authorization.k8s.io<br>roleRef:<br>  kind: Role # This must be Role or ClusterRole<br>  name: pod-reader # This must match the name of the Role or ClusterRole you wish to bind<br>  apiGroup: rbac.authorization.k8s.io</pre><p>To create this RoleBinding, save the above content as read-pods-binding.yamland run:</p><pre>kubectl apply -f read-pods-binding.yaml</pre><p>After applying this, dev-user will have permissions to get, watch, listpods only within the default namespace.</p><h3>Main Commands</h3><p>Here are some essential kubectl commands for managing RBAC resources:</p><ul><li><strong>View Roles:</strong></li></ul><pre>kubectl get roles --all-namespaces</pre><ul><li><strong>View RoleBindings:</strong></li></ul><pre>kubectl get rolebindings --all-namespaces</pre><ul><li><strong>View ClusterRoles:</strong></li></ul><pre>kubectl get clusterroles</pre><ul><li><strong>View ClusterRoleBindings:</strong></li></ul><pre>kubectl get clusterrolebindings</pre><ul><li><strong>Describe RBAC resources for detailed information:</strong></li></ul><pre># Describe a specific Role<br>kubectl describe role &lt;role-name&gt; -n &lt;namespace&gt;<br><br># Describe a specific RoleBinding<br>kubectl describe rolebinding &lt;rolebinding-name&gt; -n &lt;namespace&gt;<br><br># Describe a specific ClusterRole<br>kubectl describe clusterrole &lt;clusterrole-name&gt;<br><br># Describe a specific ClusterRoleBinding<br>kubectl describe clusterrolebinding &lt;clusterrolebinding-name&gt;</pre><ul><li><strong>Check API access for a user:</strong></li></ul><pre>kubectl auth can-i &lt;verb&gt; &lt;resource&gt; --as &lt;user-name&gt; [-n &lt;namespace&gt;]<br># Example: Check if user &#39;dev-user&#39; can create pods in &#39;default&#39; namespace<br>kubectl auth can-i create pods --as dev-user -n default</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dc0eb40bda9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kubernetes Auto-Scaling: HPA and VPA Hands-On Labs]]></title>
            <link>https://medium.com/@mohamed180235/mastering-kubernetes-auto-scaling-hpa-and-vpa-hands-on-labs-af53919ec266?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/af53919ec266</guid>
            <category><![CDATA[horizontal-pod-autoscaler]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 23:55:00 GMT</pubDate>
            <atom:updated>2025-07-31T23:55:00.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cCA6srMScXuwsY1P8lH5qw.jpeg" /></figure><p>Auto-scaling is a critical capability in Kubernetes that ensures your applications can dynamically adjust to varying loads, optimizing resource utilization and maintaining performance. Kubernetes offers two primary mechanisms for auto-scaling: Horizontal Pod Autoscaler (<strong>HPA</strong>) and Vertical Pod Autoscaler (<strong>VPA</strong>).</p><ul><li>Horizontal Pod Autoscaler (<strong>HPA</strong>): Scales the number of Pod replicas up or down based on observed CPU utilization, memory usage, or custom metrics.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8jagSjOrE6u8MoQD.png" /></figure><ul><li>Vertical Pod Autoscaler (<strong>VPA</strong>): Automatically adjusts the CPU and memory requests and limits for containers in a Pod based on their historical usage, helping to right-size your workloads.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gDz5AkTheHzi2eeA.png" /></figure><p>In this hands-on lab guide, we will explore how to implement and observe both HPA and VPA in action.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have:</p><ul><li>A running Kubernetes cluster (Minikube, Kubeadm, Kind, or a cloud-based cluster like EKS, GKE, AKS). Minikube is recommended for simplicity.</li></ul><blockquote><em>Note: you can use Kubernetes playgrounds like: </em><a href="https://killercoda.com/playgrounds/scenario/kubernetes"><strong><em>Killercoda</em></strong></a></blockquote><ul><li>kubectlconfigured to connect to your cluster.</li><li><strong>Metrics Server</strong>: HPA relies on the Metrics Server to collect resource utilization data. Ensure it’s installed in your cluster. For Minikube, it’s usually enabled by default. For others, you might need to install it:</li></ul><blockquote>Execute <strong>kubectl apply -f </strong><a href="https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml"><strong>https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml</strong></a></blockquote><blockquote>If crashes, add the following to <strong><em>containers.args</em></strong> inside the metric deployment (<strong>kubectl edit deployment metrics-server -n kube-system</strong>)</blockquote><blockquote><strong>— — kubelet-insecure-tls</strong></blockquote><blockquote><strong>— — kubelet-preferred-address-types=InternalIP</strong></blockquote><p><strong>Vertical Pod Autoscaler (VPA) Components</strong>: VPA is not installed by default. You’ll need to install its components (Admission Plugin, Recommender, Updater). The installation steps can vary, but a common way is to clone the VPA repository and apply the manifests:</p><blockquote># Clone the VPA repository<br><strong>git clone </strong><a href="https://github.com/kubernetes/autoscaler.git"><strong>https://github.com/kubernetes/autoscaler.git</strong></a><br><strong>cd autoscaler/vertical-pod-autoscaler/</strong></blockquote><blockquote># Install VPA components<br><strong>./hack/vpa-up.sh</strong></blockquote><blockquote># Verify installation<br><strong>kubectl get pods -n kube-system | grep vpa</strong></blockquote><h3>Lab 1: Horizontal Pod Autoscaler (HPA)</h3><p>Goal: Automatically scale a web application based on CPU utilization.</p><ol><li><strong>Deploy a Sample Application:</strong></li></ol><p>We’ll use a simple Nginx image that simulates CPU load when accessed.</p><p>Create a file named nginx-deploy-hpa.yaml with the following content:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-hpa-app<br>spec:<br>  selector:<br>    matchLabels:<br>      app: nginx-hpa-app<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx-hpa-app<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:latest<br>        ports:<br>        - containerPort: 80<br>        resources:<br>          limits:<br>            cpu: 500m<br>          requests:<br>            cpu: 200m<br>      - name: stress<br>        image: busybox<br>        command: [&quot;/bin/sh&quot;]<br>        args: [&quot;-c&quot;, &quot;while true; do dd if=/dev/zero of=/dev/null bs=1M count=100; done&quot;]<br>        resources:<br>          limits:<br>            cpu: 500m<br>          requests:<br>            cpu: 200m<br>---<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx<br>spec:<br>  selector:<br>    app: nginx-hpa-app<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80</pre><p>Apply the deployment:</p><pre>kubectl apply -f nginx-deploy-hpa.yaml</pre><p><strong>2. Create an HPA Resource:</strong></p><p>We’ll configure HPA to maintain an average CPU utilization of 50% across Pods, with a minimum of 1 Pod and a maximum of 5 Pods.</p><p>Create a file named hpa-nginx.yaml with the following content:</p><pre>apiVersion: autoscaling/v2<br>kind: HorizontalPodAutoscaler<br>metadata:<br>  name: nginx-hpa<br>spec:<br>  scaleTargetRef:<br>    apiVersion: apps/v1<br>    kind: Deployment<br>    name: nginx-hpa-app<br>  minReplicas: 1<br>  maxReplicas: 5<br>  metrics:<br>  - type: Resource<br>    resource:<br>      name: cpu<br>      target:<br>        type: Utilization<br>        averageUtilization: 50</pre><p>Apply the HPA:</p><pre>kubectl apply -f hpa-nginx.yaml</pre><p><strong>3. Observe HPA Status:</strong></p><pre>kubectl get hpa</pre><p>Initially, you’ll see CURRENT CPU utilization as <em>&lt;unknown&gt;</em> or low, and REPLICASas <em>1</em>.</p><p><strong>4. Generate Load to Trigger Scaling:</strong></p><p>We’ll use kubectl runto create a temporary Pod that generates continuous requests to our Nginx service, simulating high CPU load.</p><pre>kubectl run -it --rm loader --image=busybox --restart=Never -- /bin/sh -c &quot;while true; do wget -qO- http://nginx; done&quot;</pre><p><strong>5. Observe Scaling Behavior:</strong></p><p>Monitor the HPA status and Pods:</p><pre>kubectl get hpa -w<br>kubectl get pods -w</pre><p>You should see the CURRENTCPU utilization increases, and HPA will gradually increase the number of REPLICAS to bring the CPU utilization down to the target 50%. Once the load stops, HPA will scale down the replicas.</p><h3>Lab 2: Vertical Pod Autoscaler (VPA)</h3><p>Goal: Automatically adjust CPU and memory requests/limits for a Pod.</p><p><strong>1. Deploy a Sample Application for VPA (Nginx):</strong></p><p>We’ll use an Nginx application that consumes some CPU and memory.</p><p>Create a file named nginx-deploy-vpa.yaml with the following content:</p><pre># nginx-vpa.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-vpa-app<br>spec:<br>  selector:<br>    matchLabels:<br>      app: nginx-vpa-app<br>  replicas: 1<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx-vpa-app<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:latest<br>        ports:<br>        - containerPort: 80<br>        resources:<br>          requests:<br>            cpu: 100m<br>            memory: 100Mi<br>          limits:<br>            cpu: 200m<br>            memory: 200Mi</pre><p>Apply the Deployment:</p><pre>kubectl apply -f nginx-deploy-vpa.yaml</pre><p><strong>2. Create a VPA Resource:</strong></p><p>We’ll configure VPA for our nginx-vpa-app.</p><p>Create a file named vpa-nginx.yaml with the following content:</p><pre># vpa-nginx.yaml<br>apiVersion: autoscaling.k8s.io/v1<br>kind: VerticalPodAutoscaler<br>metadata:<br>  name: nginx-vpa<br>spec:<br>  targetRef:<br>    apiVersion: &quot;apps/v1&quot;<br>    kind:       Deployment<br>    name:       nginx-vpa-app<br>  updatePolicy:<br>    updateMode: &quot;Off&quot; # Or &quot;Auto&quot; for automatic updates (may restart pods)<br>  resourcePolicy:<br>    containerPolicies:<br>      - containerName: &quot;.*&quot;<br>        minAllowed:<br>          cpu: 50m<br>          memory: 50Mi<br>        maxAllowed:<br>          cpu: 1<br>          memory: 1Gi</pre><blockquote>Note on updateMode:</blockquote><blockquote>Off: VPA will only provide recommendations, but won’t apply them automatically. This is good for initial observation.</blockquote><blockquote>Auto: VPA will automatically update the Pods’ resource requests/limits. This might involve restarting Pods.</blockquote><blockquote>Recreate: VPA will delete and recreate Pods to apply new recommendations.</blockquote><p>Apply the VPA:</p><pre>kubectl apply -f vpa-nginx.yaml</pre><p><strong>3. Generate Load (Optional, but recommended for VPA to learn):</strong></p><p>For VPA to provide meaningful recommendations, the application needs to consume resources. Let’s make our Nginx container consume some CPU.</p><pre># Get the name of the Nginx VPA Pod<br>NGINX_VPA_POD_NAME=$(kubectl get pod -l app=nginx-vpa-app -o jsonpath=\&#39;{.items[0].metadata.name}\&#39;)<br><br># Execute a CPU-intensive command inside the Nginx container<br>kubectl exec -it $NGINX_VPA_POD_NAME -- /bin/sh -c &quot;while true; do dd if=/dev/zero of=/dev/null bs=1M count=100; done&quot;<br># (Let it run for a few minutes, then exit the exec session)</pre><p><strong>4. Observe VPA Recommendations:</strong></p><p>After some time (VPA Recommender runs periodically, typically every 5 minutes), you can check the VPA object for recommendations:</p><pre>kubectl get vpa nginx-vpa -o yaml</pre><p>Look for the status.recommendation section. You should see recommended CPU and memory requests/limits based on the observed usage. If updateMode was set to Auto or RecreateVPA would have applied these recommendations to the Pods.</p><h3>Cleanup</h3><p>To remove all resources created in these labs:</p><pre>kubectl delete deployment nginx-hpa-app<br>kubeclt delete service nginx-hpa-service<br>kubeclt delete hpa nginx-hpa<br><br>kubectl delete deployment nginx-vpa-app<br>kubeclt delete vpa nginx-vpa<br><br># If you installed Metrics Server and VPA components manually, you might want to uninstall them:<br># kubectl delete -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml<br># cd autoscaler/vertical-pod-autoscaler<br># ./hack/vpa-down.sh</pre><p>#Kubernetes #K8s #AutoScaling #HPA #VPA #DevOps #CloudNative #Containers #Microservices #Labs #Tutorial #ResourceManagement</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af53919ec266" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[الSecrets في Kubernetes: ليه مش آمنة زي ما أنت فاكر؟]]></title>
            <link>https://medium.com/@mohamed180235/%D8%A7%D9%84secrets-%D9%81%D9%8A-kubernetes-%D9%84%D9%8A%D9%87-%D9%85%D8%B4-%D8%A2%D9%85%D9%86%D8%A9-%D8%B2%D9%8A-%D9%85%D8%A7-%D8%A3%D9%86%D8%AA-%D9%81%D8%A7%D9%83%D8%B1-3b1d1cd4e8c5?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b1d1cd4e8c5</guid>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 07:33:42 GMT</pubDate>
            <atom:updated>2025-07-27T07:33:42.823Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/601/0*ySoC6lbXAPx6BCMH" /></figure><h3>تعرف إن الSecrets في Kubernetes مش Secure؟😮</h3><p>لو عندك UserName و Password بتاع DataBase محتاج تحفظهم عندك جوا الكلاستر تفتكر ممكن نعمل ده ازاي؟ بدون تفكير هنروح لSecret Object ف Kubernetes وده عبارة عن Object بيحفظ أي داتا زي الPasswords وأي Secret Keys وهكذا، ممكن تفتكر إن دي طريقة مثالية عشان تأمن بياناتك الحساسة جوا Kubernetes بس لما تفهم كويس إزاي Kubernetes Secrets بتشتغل هتكتشف حقيقة ممكن تكون مقلقة شوية وهي إنها مش آمنة بطبيعتها زي ما ناس كتير فاكرة وديه ممكن تكون نقطة ضعف خطيرة تتعلق بالSecurity بتاعت الأبلكيشن بتاعك</p><h3>في البداية ازاي تعمل Secret وتستخدمها في Kubernetes:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QTIqzkqEwNG7yKQY" /></figure><p>العملية ديه بتتم على مرحلتين:</p><h4>1- تعمل الSecret بأي طريقة ( Imperative أوDeclarative) :</h4><p>مثلاً عن طريق Imperative Approach</p><pre>kubectl create secret generic app-secret --from-literal=DB_Host=mysql --from-literal=DB_User=root --from-literal=DB_Password=paswrd</pre><h4>1- تInject الSecret جوا الPod :</h4><p>مثلاً عن طريق الEnvironment Variable:</p><pre>apiVersion: v1<br>kind: Pod<br>metadata:<br>  name: simple-webapp-color<br>  labels:<br>    name: simple-webapp-color<br>spec:<br>  containers:<br>    - name: simple-webapp-color<br>      image: simple-webapp-color<br>      ports:<br>        - containerPort: 8080<br>      envFrom:<br>        - secretRef:<br>            name: app-secret</pre><h3>ليه Kubernetes Secrets مش آمنة بشكل افتراضي؟</h3><p>مع إن Kubernetes Secrets معموله عشان تخزن البيانات الحساسة بس فيه كذا نقطة بتخليها مش آمنة بشكل افتراضي وده بيخليك لازم تاخد بالك كويس وانت بتستخدمها. ودي أهم النقط دي:</p><h4>1. مفيش تشفير وهي متخزنة (Lack of Encryption at Rest)</h4><p>واحدة من أكبر المفاهيم الغلط عن Kubernetes Secrets إنها بتتشفّر لوحدها لما تتخزن والحقيقة إن البيانات في Kubernetes Secrets بتتشفر باستخدام Base64 بس، وده مش تشفير خالص دي مجرد طريقة عشان تحول البيانات. أي حد عنده صلاحية يوصل لـ Secret اللي متشفر بـ Base64 يقدر بسهولة يفك تشفيره ويرجع القيمة الأصلية. ده معناه إن الـ Secret اللي متخزن في etcd (قاعدة البيانات الأساسية لـ Kubernetes) بيكون مكشوف لو مهاجم قدر يوصل لـ etcd.</p><p>تخيل إن عندنا Secret بسيط فيه اسم مستخدم وباسورد:</p><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: my-secret<br>type: Opaque<br>data:<br>  username: dXNlcg==<br>  password: cGFzc3dvcmQ=</pre><p>لو مهاجم قدر يوصل للـ Secret ديه هيقدر بسهولة يفك تشفير dXNlcg== و cGFzc3dvcmQ= بأي أداة لفك تشفير Base64 (أو حتى أمر بسيط في سطر الأوامر)</p><pre>echo &quot;dXNlcg==&quot; | base64 -d<br>echo &quot;cGFzc3dvcmQ=&quot; | base64 -d</pre><p>وهيكتشف إن اسم المستخدم هو <em>user </em>والباسورد هي <em>password</em></p><h4>2. تخزينها في etcd</h4><p>بشكل افتراضي Kubernetes بتخزن Secrets في etcd ودي قاعدة بيانات للكلاستر (Distributed Key-Value Store). ومع إن etcd ممكن تكون مشفرة بس هي مش مصممة عشان تكون حل تخزين آمن للبيانات الحساسة على المدى الطويل لو مهاجم قدر يوصل لـ etcd هيقدر يوصل لكل Secrets اللي مش مشفرة وهي متخزنة</p><h4>3. مفيش أي Logging and Auditing لاستخدام الSecrets</h4><p>غالباً بيكون فيه نقص في اLogging and Auditing للوصول للـ Secrets من غير سجلات مفصلة بيبقى صعب تتبع مين وصل للـ Secrets وإمتى وده بيخلي اكتشاف أي اختراقات محتملة صعب جداً.</p><h3>أحسن الطرق عشان تزود أمان Kubernetes Secrets</h3><p>مع كل نقط الضعف اللي ذكرناها فوق، لسه ممكن تستخدم Kubernetes Secrets بأمان لو اتبعت أحسن الممارسات الأمنية، ودي شوية نصايح مهمة:</p><h3>1. التشفير وهي متخزنة (Encryption at Rest)</h3><p>لازم دايماً تفعل تشفير البيانات وهي متخزنة في etcd ده بيضمن إن الـ Secrets اللي متخزنة في etcd مشفرة بجد حتى لو مهاجم قدر يوصل لـ etcd. العملية دي بتحتاج إعدادات زيادة في Kubernetes API Server، عشان تستخدم مفتاح تشفير عشان تشفر البيانات قبل ما تتخزن في etcd وممكن تعمل ده من هنا: <a href="https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/">https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h8YNSSnZlJlvRlVT.png" /></figure><h3>2. التحكم في الوصول للSecrets عن طريق (RBAC)</h3><p>طبق مبدأ (Principle of Least Privilege) باستخدام <strong>Kubernetes RBAC</strong>. ده معناه إنك تدي للمستخدمين والـ Pods أقل صلاحيات ممكنة عشان يعملوا شغلهم. مثلاً متديش صلاحية list أو watch على Secrets إلا للمكونات الضرورية جداً على مستوى الكلاستر. بالنسبة للمستخدمين متسمحش بالوصول المباشر إلا لAdmin User بس</p><h3>3. استخدام أدوات(External Secret Management Tools)</h3><p>عشان تزود الأمان أكتر فكر تستخدم أدوات Secret Management الخارجية زي HashiCorp Vault أو AWS Secret Manager ، الأدوات دي مصممة مخصوص عشان تخزن الداتا بأمان، وبتوفر مميزات متقدمة زي الSecret Rotation والLogging and Auditing.</p><p>الـ Kubernetes Secrets Store CSI Driver ممكن يربط الأدوات دي بـ Kubernetes وده بيسمح للـ Pods إنها توصل للsecrets ديه من الExternal Secret Stores دي من غير ما تتخزن مباشرة في etcd</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-96IcZIUyo7Q63bU" /></figure><p>#kubernetes #k8s #DevOps CloudNative #containers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b1d1cd4e8c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ال Auto Scaling في Kubernetes]]></title>
            <link>https://medium.com/@mohamed180235/%D8%A7%D9%84-auto-scaling-%D9%81%D9%8A-kubernetes-792403309e00?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/792403309e00</guid>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[arabic]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[autoscaling]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Fri, 25 Jul 2025 20:52:32 GMT</pubDate>
            <atom:updated>2025-07-26T09:36:38.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>الAuto Scaling في Kubernetes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/889/0*RWETirjB7_jmgkwN" /></figure><p>في بداية رحلة تعلم الـ DevOps بنسمع دايماً عن مفهوم “الـ Auto Scaling”! طب تعرف ازاي نطبق المفهوم ده في Kubernetes؟ 🤔</p><p>عشان نجاوب على السؤال ده لازم نتكلم عن حاجتين مهمين جداً في Kubernetes وهما الـ Horizontal Pod Autoscaler (HPA) والـ Vertical Pod Autoscaler (VPA)</p><p><strong>في البداية خلينا نعرف الفرق بين الـ HPA والـ VPA بكل بساطة</strong>تخيل إن عندك مطعم وبدأ الزباين يزيدوا. هتعمل إيه؟ عندك حلين:الـ HPA (Horizontal Pod Autoscaler): زي إنك تفتح فروع جديدة للمطعم. يعني بيزود عدد الـ Pods عشان يوزع ال Traffic عليهمالـ VPA (Vertical Pod Autoscaler): زي إنك توسع المطعم الحالي وتزود المساحة بتاعته وعدد الترابيزات مثلا. يعني بيزود الـ CPU والـ Memory للـ Pod الواحدة</p><p><strong>طيب دلوقتي إزاي اختار بين الـ HPA والـ VPA؟</strong>الاختيار بين الـ HPA والـ VPA هيكون بناءً على نوع الأبلكيشن بتاعك بمعني:</p><p><strong>نقدر نستخدم الـ HPA:</strong>- لو التطبيق بتاعنا Stateless (Deployment) وسهل انك تشغل أكتر من نسخة منه- أو لو بيحصل تغيير كتير في حجم ال Traffic بتاعك (زي مواقع الأخبار أو التجارة الإلكترونية)- و لو محتاج تحقق مفهوم زي ال elasticity (إن الأبلكيشن بتاعك يكون مرن مع عدد ال Traffic اللي عليه) يبقي ال HPA هو الاختيار المناسب في الحالة ديه</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*--duJ5F3jvW-1SWk.png" /></figure><p><strong>ونقدر نستخدم الـ VPA:</strong>- في حالة إن التطبيق بتاعنا Stateful (Statefulset) أو صعب انك تاخد منه اكتر من نسخة في نفس الوقت- أو إن الأبلكيشن بتاعك يكون بيدخل في مشاكل الـ OOMKills أو الـ CPU throttling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*NY2IkpZqnRcAKoIL" /></figure><p>يعني على سبيل المثال:</p><p>تخيل إن عندك موقع تجارة إلكترونية، وفي موسم البلاك فرايداي بيزيد عدد المستخدمين 10 أضعاف. هنا الـ HPA هيساعدك إنك تتعامل مع الضغط ده بصورة تلقائية:</p><pre>apiVersion: autoscaling/v2kind: HorizontalPodAutoscalermetadata: name: online-storespec: scaleTargetRef: apiVersion: apps/v1 kind: Deployment name: online-store minReplicas: 5 maxReplicas: 50 metrics: - type: Resource resource: name: cpu target: type: Utilization averageUtilization: 70</pre><p>في المثال ده لما استخدام الـ CPU يوصل لـ 70% الـ HPA هيبدأ يزود عدد الـ Pods من 5 لحد 50 بشكل تلقائي وده هيضمن إن الموقع مش هيقع تحت ال Traffic العالي ده — — — لكن في حالة تطبيقات قواعد البيانات زي MongoDB أو Elasticsearch اللي بتحتاج Resources كتيرة وبتختلف حسب حجم البيانات. الـ VPA بيكون هو الحل المناسب بحيث يقدر يعدل الـ CPU والـ Memory المخصصين للـ Pod بناءً على الاستخدام الفعلي لها:</p><pre>apiVersion: autoscaling.k8s.io/v1kind: VerticalPodAutoscalermetadata: name: elasticsearch-vpaspec: targetRef: apiVersion: &quot;apps/v1&quot; kind: StatefulSet name: elasticsearch updatePolicy: updateMode: &quot;Auto&quot;</pre><p>في المثال ده لما استخدام ال Resources (CPU, Memory) يزيد هيبدأ ال VPA يزود ال Resources المطلوبة بصورة اوتوماتيك (updateMode: “Auto”)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=792403309e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Kubernetes Services: A Hands-On Lab Guide]]></title>
            <link>https://medium.com/@mohamed180235/mastering-kubernetes-services-a-hands-on-lab-guide-f0ad7426e0a0?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ad7426e0a0</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[k8s]]></category>
            <category><![CDATA[services]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 22:45:34 GMT</pubDate>
            <atom:updated>2025-07-02T22:45:34.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tgeTNWS4QwGM12Squm8KsQ.png" /></figure><p>Kubernetes Services are fundamental to making your applications discoverable and accessible, both within and outside your cluster. They provide a stable network endpoint for a set of Pods, abstracting away the ephemeral nature of Pod IPs. In this lab guide, we’ll walk through practical examples of the most common Kubernetes Service types: ClusterIP, NodePort, and LoadBalancer.</p><p>By the end of this guide, you’ll have a solid understanding of how each Service type works and when to use it.</p><h3>Prerequisites</h3><p>Before you begin, make sure you have:</p><ul><li>A running Kubernetes cluster (Minikube, or a cloud-based cluster like EKS, GKE, AKS).</li></ul><blockquote><em>Note: you can use Kubernetes playgrounds like: </em><a href="https://killercoda.com/playgrounds/scenario/kubernetes"><strong><em>Killercoda</em></strong></a></blockquote><ul><li><em>kubectl</em> configured to connect to your cluster.</li></ul><p><strong>Lab 1: ClusterIP Service (Internal Communication)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*v-nFxHQPQaiD1nlzgr9AqQ.png" /></figure><p><strong>Scenario</strong>: You have a backend service (Nginx) that needs to be accessed by a frontend service running in the same cluster.</p><p>1. Create a Deployment for Nginx:</p><p>This Deployment will create Pods running Nginx.</p><pre># nginx-deployment.yaml<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: nginx-deployment<br>  labels:<br>    app: nginx<br>spec:<br>  replicas: 2<br>  selector:<br>    matchLabels:<br>      app: nginx<br>  template:<br>    metadata:<br>      labels:<br>        app: nginx<br>    spec:<br>      containers:<br>      - name: nginx<br>        image: nginx:latest<br>        ports:<br>        - containerPort: 80</pre><p>Apply the Deployment:</p><pre>kubectl apply -f nginx-deployment.yaml</pre><p>Verify Pods are running:</p><pre>kubectl get pods -l app=nginx</pre><p>2. Create a ClusterIP Service:</p><p>This Service will expose the Nginx Pods internally.</p><pre># nginx-clusterip-service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-clusterip-service<br>spec:<br>  selector:<br>    app: nginx # Selects Pods with the label app: nginx<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80<br>  type: ClusterIP # Explicitly define ClusterIP type</pre><p>Apply the Service:</p><pre>kubectl apply -f nginx-clusterip-service.yaml</pre><p>Verify the Service:</p><pre>kubectl get svc nginx-clusterip-service</pre><p>You should see an <strong>IP</strong> assigned under <strong>CLUSTER-IP</strong>.</p><p>3. Test Internal Access:</p><p>To test, we’ll create a temporary Pod and try to access <strong>Nginx </strong>through its <strong>ClusterIP</strong> Service.</p><pre>kubectl run -it --rm --restart=Never busybox --image=busybox -- /bin/sh</pre><p>Inside the busybox Pod, try to wget the Nginx Service:</p><pre>wget -O- http://nginx-clusterip-service</pre><p>You should see the Nginx welcome page HTML. This confirms internal access.</p><p><strong>Lab 2: NodePort Service (External Access for Dev/Testing)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*b-lXoKmxunJwops5X4iN-w.png" /></figure><p><strong>Scenario:</strong> You want to quickly test your application from outside the cluster without setting up a full Load Balancer.</p><p>1. Create a NodePort Service:</p><p>We’ll modify the previous Service or create a new one with type: <em>NodePort</em>.</p><pre># nginx-nodeport-service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-nodeport-service<br>spec:<br>  selector:<br>    app: nginx<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80<br>      nodePort: 30080 # Optional: Kubernetes will assign if not specified (range 30000-32767)<br>  type: NodePort</pre><p>Apply the Service:</p><pre>kubectl apply -f nginx-nodeport-service.yaml</pre><p>Verify the Service:</p><pre>kubectl get svc nginx-nodeport-service</pre><p>Note the PORT(S) column, it will show 80:30080/TCP (or a different assigned NodePort).</p><p>2. Get Node IP:</p><p>Find the IP address of one of your Kubernetes Nodes:</p><pre>kubectl get nodes -o wide</pre><p>3. Test External Access:</p><p>Open your web browser and navigate to http://&lt;Node-IP&gt;:&lt;NodePort&gt; (e.g., <a href="http://192.168.49.2:30080).">http://192.168.49.2:30080).</a></p><p>You should see the Nginx welcome page. This confirms external access via NodePort.</p><p><strong>Lab 3: LoadBalancer Service (External Access for Production)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*qaCV0KdQ0P5wKYe93EMMyQ.png" /></figure><p><strong>Scenario</strong>: You want to expose your production-ready application to the internet with high availability and proper load distribution.</p><blockquote>Note: This lab requires a Kubernetes cluster running on a cloud provider (AWS EKS, GKE, Azure AKS, etc.) that supports LoadBalancer Services. Minikube can simulate this, but a real cloud environment will give you a better understanding.</blockquote><p>1. Create a LoadBalancer Service:</p><pre># nginx-loadbalancer-service.yaml<br>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: nginx-loadbalancer-service<br>spec:<br>  selector:<br>    app: nginx<br>  ports:<br>    - protocol: TCP<br>      port: 80<br>      targetPort: 80<br>  type: LoadBalancer</pre><p>Apply the Service:</p><pre>kubectl apply -f nginx-loadbalancer-service.yaml</pre><p>2. Verify the Service and Get External IP:</p><p>It might take a minute or two for the cloud provider to provision the Load Balancer.</p><pre>kubectl get svc nginx-loadbalancer-service</pre><p>Keep running the command until you see an EXTERNAL-IP assigned (it will be &lt;pending&gt; initially).</p><p>3. Test External Access:</p><p>Once the <strong>EXTERNAL-IP</strong> is assigned, open your web browser and navigate to http://&lt;EXTERNAL-IP&gt;.</p><p>You should see the Nginx welcome page. This confirms external access via a cloud Load Balancer.</p><h3><strong>Cleanup</strong></h3><p>To remove the resources created in these labs:</p><pre>kubectl delete -f nginx-deployment.yaml<br>kubectl delete -f nginx-clusterip-service.yaml<br>kubectl delete -f nginx-nodeport-service.yaml<br>kubectl delete -f nginx-loadbalancer-service.yaml</pre><p>#Kubernetes #K8s #Services #ClusterIP #NodePort #LoadBalancer #DevOps</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ad7426e0a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying MySQL with Kubernetes StatefulSets and Headless Services: A Practical Guide]]></title>
            <link>https://medium.com/@mohamed180235/deploying-mysql-with-kubernetes-statefulsets-and-headless-services-a-practical-guide-c31c3248a521?source=rss-873c55cee36d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c31c3248a521</guid>
            <category><![CDATA[statefulsets]]></category>
            <category><![CDATA[cloud-native]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[k8s]]></category>
            <dc:creator><![CDATA[Mohamed Rabie]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 23:19:00 GMT</pubDate>
            <atom:updated>2025-06-28T23:19:00.620Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*0p4PS03L1FCrQpZbuJ4ZSQ.png" /></figure><p>Kubernetes has revolutionized how we deploy and manage stateless applications. However, handling stateful applications like databases (e.g., MySQL, PostgreSQL) in a cloud-native environment presents unique challenges. This is where Kubernetes StatefulSets, combined with Headless Services, come into play.</p><p>In this article, we’ll dive into a practical example of deploying a MySQL database using a StatefulSet, ensuring data persistence, stable network identities, and ordered deployment/scaling. We’ll also explore the crucial role of Headless Services in enabling direct communication between database instances.</p><h3>Why StatefulSets for Databases?</h3><p>Traditional Deployments are great for stateless applications where Pods are interchangeable. But databases require:</p><p>1. Stable, Unique Network Identifiers: Each database instance needs a consistent hostname to be discoverable by other instances (e.g., for replication).</p><p>2. Stable, Persistent Storage: Data must survive Pod restarts or rescheduling. Each instance needs its own dedicated, persistent storage.</p><p>3 . Ordered Deployment and Scaling: For clustered databases, it’s often critical to deploy and scale instances in a specific order (e.g., master before replicas).</p><p>StatefulSets provide these guarantees, making them the ideal choice for stateful applications.</p><h3>The Role of Headless Services</h3><p>A Headless Service is a special type of Kubernetes Service (defined by clusterIP: None) that doesn’t provide load balancing. Instead, it allows direct access to individual Pods by their unique DNS names. This is vital for StatefulSets because:</p><p>•It enables stable network identities for each Pod in the StatefulSet.</p><p>•It facilitates direct peer-to-peer communication between Pods, which is essential for database replication or clustering.</p><ul><li>It allows service discovery based on individual Pod hostnames (e.g., mysql-0.mysql-headless.default.svc.cluster.local).</li></ul><h3>Practical Example: Deploying MySQL</h3><p>Let’s deploy a simple MySQL database using a StatefulSet and a Headless Service. We’ll create a 3-replica MySQL setup.</p><blockquote>Note: you can use Kubernetes playgrounds like: <a href="https://killercoda.com/playgrounds/scenario/kubernetes"><strong>Killercoda</strong></a></blockquote><h4>Step 1: Define the Headless Service</h4><p>First, create a Headless Service. This service will expose the Pods of our StatefulSet directly.</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mysql-headless<br>  labels:<br>    app: mysql<br>spec:<br>  ports:<br>  - port: 3306<br>    name: mysql<br>  clusterIP: None # This makes it a Headless Service<br>  selector:<br>    app: mysql # Selects Pods with the label app: mysql</pre><p>Save this as mysql-headless-service.yaml and apply it:</p><pre>kubectl apply -f mysql-headless-service.yaml</pre><h4>Step 2: Define the StatefulSet</h4><p>Now, let’s define the StatefulSet for our MySQL instances. Notice how serviceName links it to our Headless Service and volumeClaimTemplates handles persistent storage for each Pod.</p><pre>apiVersion: apps/v1<br>kind: StatefulSet<br>metadata:<br>  name: mysql<br>spec:<br>  serviceName: &quot;mysql-headless&quot; # Link to the Headless Service<br>  replicas: 3<br>  selector:<br>    matchLabels:<br>      app: mysql<br>  template:<br>    metadata:<br>      labels:<br>        app: mysql<br>    spec:<br>      containers:<br>      - name: mysql<br>        image: mysql:8.0<br>        ports:<br>        - containerPort: 3306<br>          name: mysql<br>        env:<br>        - name: MYSQL_ROOT_PASSWORD<br>          value: password # Replace with a strong password or use Secrets<br>        volumeMounts:<br>        - name: mysql-persistent-storage<br>          mountPath: /var/lib/mysql # Default MySQL data directory<br>  volumeClaimTemplates:<br>  - metadata:<br>      name: mysql-persistent-storage<br>    spec:<br>      accessModes: [&quot;ReadWriteOnce&quot;]<br>      resources:<br>        requests:<br>          storage: 1Gi # Request 1GB of storage for each Pod</pre><p>Save this as mysql-statefulset.yaml and apply it:</p><pre>kubectl apply -f mysql-statefulset.yaml</pre><h4>Step 3: Verify the Deployment</h4><p>After applying the manifests, Kubernetes will start creating the Pods in an ordered manner (mysql-0, then mysql-1, then mysql-2). You can monitor their status:</p><pre>kubectl get pods -l app=mysql<br>kubectl get pvc -l app=mysql<br>kubectl get svc mysql-headless</pre><p>You should see three Pods (mysql-0, mysql-1, mysql-2) in a Running state, and three PersistentVolumeClaims created for them. The mysql-headless service should also be present.</p><p>And try to describe this statefulset:</p><pre>kubectl describe statefulsets.apps mysql</pre><p>You should see the events as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kmguDgpOw9kFdtDGtsLyQ.png" /></figure><h4>Step 4: Test Connectivity and Data Persistence</h4><p>To test, you can exec into one of the Pods and connect to the MySQL server:</p><pre>kubectl exec -it mysql-0 -- mysql -p<br># Enter the password &#39;password&#39; (or your chosen password)<br><br># Inside MySQL, create a database<br>CREATE DATABASE my_test_db;<br>SHOW DATABASES;<br>EXIT;</pre><p>Now, if you delete the mysql-0 Pod, Kubernetes will recreate it, and it will attach to the same PersistentVolumeClaim, ensuring your data is still there:</p><pre>kubectl delete pod mysql-0<br># Wait for the new mysql-0 Pod to be Running<br>kubectl exec -it mysql-0 -- mysql -p<br># Enter password<br>SHOW DATABASES;<br># You should see &#39;my_test_db&#39;<br>EXIT;</pre><h3>Conclusion</h3><p>Deploying stateful applications like databases in Kubernetes is made robust and reliable with StatefulSets and Headless Services. This combination provides the necessary stable identities, persistent storage, and ordered operations crucial for production-grade stateful workloads. By understanding these core concepts and their practical implementation, you can confidently manage even the most demanding applications in your Kubernetes clusters.</p><p>#Kubernetes #K8s #StatefulSet #HeadlessService #MySQL #DevOps #CloudNative #Containers #PersistentStorage #DatabaseDeployment</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c31c3248a521" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>