Make Your Kubernetes Apps Self-heal With Argo Cd And Gitops

Sedang Trending 1 bulan yang lalu

Kubernetes applications successful accumulation traditionally require manual activity and time.

GitOps pinch Argo CD solves this. It keeps your cluster successful sync pinch git, wherever your repository defines nan desired state. Argo CD makes judge nan cluster ever matches it, and erstwhile thing falters, it fixes itself automatically. With GitOps, your applications go self-healing and ever enactment successful sync pinch git.

What Is GitOps and Self-Healing?

GitOps intends your git repository is nan azygous root of truth for everything. When reality doesn’t lucifer git, nan strategy automatically fixes itself.

Your app’s configurations are stored successful git, and immoderate changes to either your app aliases nan git root codification will automatically beryllium fixed. This is GitOps astatine its finest and astir elemental opportunity to accelerate nan accepted deployment process.

Rejuvenating Traditional Deployment

When you travel nan accepted deployment process, location are galore scenarios wherever things mightiness return an unexpected turn:

  • Someone tin manually alteration nan accumulation settings, and your accumulation mightiness halt.
  • A method misstep connected nan server tin region production, past you person to manually restart it.
  • Your app configuration changes, and you person to support way of what was changed.

GitOps handles each these possibilities efficaciously and pinch simplicity.

GitOps Self-Healing Solution

With GitOps, you tin support nan existent authorities of your exertion successful a git repository. GitOps tech for illustration Argo CD ensures that immoderate is defined successful your git matches nan existent app deployment.

If location are method hiccups connected nan server, GitOps will automatically resoluteness them and reconstruct your app to nan defined state. This is known arsenic self-healing successful GitOps.

On apical of that, you besides support an audit way of each nan changes made successful git.

Step 0: Prerequisites

  • Docker is installed connected your system.
  • My go-to: WSL2 pinch Ubuntu. Feel free to usage your ain Linux setup.
  • GitHub account.
  • Docker Hub account.
  • My go-to: React task (You tin usage immoderate project).
  • Knowledge of Kubernetes (optional).

Step 1: Install and Start Minikube

First, group up a Kubernetes cluster. For this tutorial, we will usage Minikube. It’s lightweight and perfect for learning.

(You tin skip this measurement if you already person a cluster moving locally.)

Install Minikube

Run nan commands beneath to instal Minikube:

# Download and instal minikube

curl -LO https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64

sudo install minikube-linux-amd64 /usr/local/bin/minikube

# Install kubectl if you don't person it

curl -LO "https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"

sudo install -o root -g root -m 0755 kubectl /usr/local/bin/kubectl

# Note: Some Linux distributions request this for Minikube

sudo apt install conntrack

Start Minikube Cluster

Before moving nan bid below, make judge Docker is running.

# Start minikube pinch Docker driver

minikube start --driver=docker

# Verify everything is working

kubectl version --client

kubectl get nodes

# You should see:

# NAME       STATUS   ROLES           AGE

# minikube   Ready    control-plane   1m

# Enable ingress addon (useful for later)

minikube addons enable ingress

Step 2: Create Your React App

# Create nan app

cd ~/projects

npx create-react-app my-selfhealing-app

cd my-selfhealing-app

Update nan App for Demo

Replace src/app.js:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

import './App.css';

import { useState, useEffect } from 'react';

function App() {

  const [count, setCount] = useState(0);

  const [timestamp, setTimestamp] = useState('');

  useEffect(() => {

    setTimestamp(new Date().toLocaleString());

  }, []);

  return (

    <div className="App">

      <header className="App-header">

        <h1>🛡️ Self-Healing React App</h1>

        <p>This app automatically fixes itself using GitOps!</p>

        <div style={{

          background: 'rgba(255,255,255,0.1)',

          padding: '20px',

          borderRadius: '10px',

          margin: '20px 0'

        }}>

          <button

            onClick={() => setCount(count + 1)}

            style={{

              padding: '10px 20px',

              fontSize: '16px',

              backgroundColor: '#61dafb',

              border: 'none',

              borderRadius: '5px',

              cursor: 'pointer'

            }}

          >

            Clicked {count} times

          </button>

        </div>

        <div style={{ fontSize: '14px', opacity: 0.8 }}>

          <p>🔄 Auto-sync enabled</p>

          <p>🛠️ Self-healing active</p>

          <p>📅 Deployed: {timestamp}</p>

          <p>🏷️ Version: 1.0.0</p>

        </div>

      </header>

    </div>

  );

}

export default App;


Note: This codification should activity fine. You tin besides usage Vite aliases immoderate different framework, since CRA is deprecated.

Create Dockerfile

A Dockerfile is utilized to constitute nan Docker codebase.

Create Dockerfile:

Make judge to put this record successful nan guidelines of nan project. Paste nan codification beneath into it.

FROM node:18-alpine as builder

WORKDIR /app

COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build

FROM nginx:alpine

COPY --from=builder /app/build /usr/share/nginx/html

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]


Here, we are first installing nan node, past creating a build, past pursuing instructions connected moving nan exertion connected larboard 80.

Push to GitHub

Once each your codification is ready, push it to GitHub.

git init

git add .

git commit -m "Initial self-healing app"

git branch -M main

git remote add origin https://github.com/YOUR_USERNAME/my-selfhealing-app.git

git push -u origin main

Step 3: Build and Push Docker Image

Now that nan codification is ready, create a Docker image and push it to Docker Hub.

If you don’t person a Docker Hub account, you tin motion up and create 1 from nan Docker Hub page.

Also, make judge Docker is moving locally. If you don’t person Docker installed locally, you tin instal Docker Desktop.

# Build nan image

docker build -t YOUR_DOCKERHUB_USERNAME/selfhealing-app:v1.0.0 .

# Push to DockerHub

docker login

docker push YOUR_DOCKERHUB_USERNAME/selfhealing-app:v1.0.0

Step 4: Create GitOps Configuration Repository

To get started pinch GitOps, create a caller git repository. This is important because it’s imaginable to person abstracted repositories for root codification and GitOps.

# Build nan image

docker build -t YOUR_DOCKERHUB_USERNAME/selfhealing-app:v1.0.0 .

# Push to DockerHub

docker login

docker push YOUR_DOCKERHUB_USERNAME/selfhealing-app:v1.0.0

Create Kubernetes Manifests

First, create a caller files called “app.” Inside this folder, create Kubernetes-related files.

Create app/deployment.yaml:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

apiVersion: apps/v1

kind: Deployment

metadata:

  name: selfhealing-app

  namespace: default

spec:

  replicas: 2  # We are having 2 replicas of our app

  selector:

    matchLabels:

      app: selfhealing-app

  template:

    metadata:

      labels:

        app: selfhealing-app

    spec:

      containers:

      - name: react-app

        image: YOUR_DOCKERHUB_USERNAME/selfhealing-app:v1.0.0  # Update this!

        ports:

        - containerPort: 80

        resources:

          requests:

            memory: "64Mi"

            cpu: "50m"

          limits:

            memory: "128Mi"

            cpu: "100m"


This is simply a regular Kubernetes deployment record pinch basal details. Make judge to update nan image pinch your Docker image.

Next, create different record for nan Kubernetes service.

Create app/service.yaml:

apiVersion: v1

kind: Service

metadata:

  name: selfhealing-app-service

  namespace: default

spec:

  selector:

    app: selfhealing-app

  ports:

  - port: 80

    targetPort: 80

  type: LoadBalancer

Commit GitOps Configuration

Once each nan files are created, push nan changes to GitHub.

git add .

git commit -m "Add GitOps configuration for self-healing app"

git push origin main

Step 5: Install Argo CD

Next, instal nan instrumentality that makes self-healing possible.

# Create Argo CD namespace

kubectl create namespace Argo CD

# Install Argo CD

kubectl apply -n Argo CD -f https://raw.githubusercontent.com/argoproj/argo-cd/stable/manifests/install.yaml

# Wait for it to beryllium fresh (takes 2-3 minutes)

echo "Installing Argo CD... this takes a fewer minutes"

kubectl wait --for=condition=available --timeout=300s deployment/Argo CD-server -n Argo CD

Access Argo CD

# Get nan admin password

echo "Argo CD Password:"

kubectl -n Argo CD get secret Argo CD-initial-admin-secret -o jsonpath="{.data.password}" | base64 -d && echo

# It will springiness output thing for illustration this. Keep nan password handy. Username is admin.

# Argo CD Password:

#Gvy5q5gb3kADdS3w

# Start larboard forwarding (keep this running)

kubectl port-forward svc/Argo CD-server -n Argo CD 8080:443 > /dev/null 2>&1 &

echo "Argo CD UI: https://localhost:8080"


Now Argo CD will tally connected larboard 8080. Open this URL successful your browser: https://localhost:8080.

You would spot a login surface for illustration this:

AgroCD login screen

AgroCD login screen.

You tin usage nan username “admin” and nan password that you person conscionable generated utilizing nan supra command. Once nan login is done, it’s clip to create an exertion wrong Argo CD.

Step 6: Create Self-Healing Application

Tell Argo CD to negociate your app and alteration self-healing.

Create Argo CD Application

Create selfhealing-application.yaml:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

apiVersion: argoproj.io/v1alpha1

kind: Application

metadata:

  name: selfhealing-app

  namespace: Argo CD

spec:

  project: default

  source:

    repoURL: https://github.com/YOUR_USERNAME/my-GitOps-config  # Update this!

    targetRevision: HEAD

    path: app

  destination:

    server: https://kubernetes.default.svc

    namespace: default

  syncPolicy:

    automated:

      prune: true      # Remove other resources

      selfHeal: true   # THE MAGIC: Auto-fix erstwhile things drift


Apply it:

# Update nan repoURL first, then:

kubectl apply -f selfhealing-application.yaml

# This will springiness nan consequence below

# application.argoproj.io/selfhealing-app configured


Once this is done, you should spot your exertion successful your Argo CD dashboard.

Argo CD UI showing that it  is moving locally

Argo CD UI showing that it is moving locally.

Step 7: Access Your Self-Healing App

# Check pods are running

kubectl get pods -l app=selfhealing-app


It should show thing for illustration this:

Output showing that pods are running

Output showing that pods are running.


# Access your app utilizing port-forward

kubectl port-forward svc/selfhealing-app-service 3000:80 > /dev/null 2>&1 &

Visit http://localhost:3000 to spot your app running.

Initial app pinch first version

Initial app pinch first version.

Step 8: Test Self-Healing 

It’s clip to trial nan changes and spot nan self-healing process successful action.

Deleting a Pod

Start by simply deleting a pod.

# See your pods

kubectl get pods -l app=selfhealing-app

#You should spot 2 pods

#NAME                               READY   STATUS    RESTARTS      AGE

#selfhealing-app-58cb69c845-ndssn   1/1     Running   1 (47m ago)   43h

#selfhealing-app-58cb69c845-swsf6   1/1     Running   1 (47m ago)   43h

# Delete 1 pod

kubectl delete pod -l app=selfhealing-app

# Watch it get recreated immediately

kubectl get pods -l app=selfhealing-app

#Now, moreover aft deleting your pods, you will still spot 2 pods.


This is basal Kubernetes behavior, but now let’s spot Argo CD’s self-healing …

Delete nan Entire Deployment

Now, spell 1 measurement further by deleting everything.

# The eventual trial - delete everything!

kubectl delete deployment selfhealing-app

kubectl delete service selfhealing-app-service

# Watch Argo CD recreate everything automatically

kubectl get all -l app=selfhealing-app -w

Argo CD app status, showing sync clip and different details

Argo CD app status, showing sync clip and different details.

The Argo CD dashboard will show sync clip arsenic “a fewer seconds ago.” This shows that it has already synced and created nan exertion again. In different words, Argo CD ensures reality ever matches git.

Step 9: Making Real Updates (The GitOps Way)

Now, make a morganatic alteration to spot really GitOps handles updates.

Update Your App

Edit src/App.js and change:

<p>🏷️ Version: 2.0.0 - Updated via GitOps!</p>


This update reflects a caller type of nan app. A elemental change.

Build and Push New Version

Now, create a caller Docker build and push it to nan Docker Hub. Also, push nan root codification to GitHub.

cd ~/projects/my-selfhealing-app

# Build and push caller version

docker build -t YOUR_DOCKERHUB_USERNAME/selfhealing-app:v2.0.0 .

docker push YOUR_DOCKERHUB_USERNAME/selfhealing-app:v2.0.0

# Commit app changes

git add .

git commit -m "Update to type 2.0.0"

git push origin main

Update GitOps Configuration

Next, unfastened nan GitOps repository and usage nan update app/deployment.yaml file, updating nan image way successful nan app/deployment.yaml record for nan caller Docker image.

image: YOUR_DOCKERHUB_USERNAME/selfhealing-app:v2.0.0


Next, push changes to nan GitOps repo.

# Commit nan configuration change

git add .

git commit -m "Deploy type 2.0.0"

git push origin main

Watch Automatic Deployment

Within minutes, Argo CD will:

  1. Notice nan git repository changed.
  2. Pull nan caller configuration.
  3. Update nan moving application.
  4. Show “Synced” position successful nan UI.

By default, Argo CD checks for changes each 3 minutes. You tin set this to make it cheque faster (near existent time) aliases slower (less frequent).

Visit http://localhost:3000 to spot your updated app.

Make judge to do larboard forwarding earlier checking.

kubectl port-forward svc/selfhealing-app-service 3000:80 > /dev/null 2>&1 &


Now, you will spot nan updated UI.

Final app showing self-healed authorities pinch caller version

Final app showing self-healed authorities pinch caller version.

This surface intends you person completed nan GitOps setup. Now your apps will automatically beryllium deployed and heal themselves whenever needed.

Understanding nan Self-Healing Magic

Here’s nan workflow that makes self-healing possible: 

  1. Argo CD keeps watching nan git repository. It besides watches your Kubernetes cluster.
  2. It continuously compares nan configuration defined successful git and nan existent Kubernetes structure.
  3. If it finds a difference, it signals Kubernetes to set arsenic defined successful git.

This is nan self-healing process.

Image showing GitOps workflow

Image showing GitOps workflow.

GitOps Is nan Future (And Present)

Every clip you push to git, your app updates. When accumulation stops, your app heals itself. This is much than deployment automation. It is simply a self-healing infrastructure. It takes attraction of itself while giving you backmost clip to activity connected different things. That’s nan powerfulness of GitOps.

YOUTUBE.COM/THENEWSTACK

Tech moves fast, don't miss an episode. Subscribe to our YouTube channel to watercourse each our podcasts, interviews, demos, and more.

Group Created pinch Sketch.

Selengkapnya