Technology

Deploy React App to Kubernetes Cluster

Kubernetes has been a standard in the industry for deploying containerized applications in the cloud. There are many cloud providers like(Google cloud, AWS, etc) that provide its services for deploying our application to the cloud using kubernetes or their own environment.

Here are some of the reasons for choosing Kubernetes to deploy your React application:

  • Kubernetes provides us with a standardized and unified deployment system for all the cloud providers.
  • Kubenetes has more advanced deployment features such as blue green and canary deployments.
  • Kubernetes have the capability to handle peak traffic.
  • Kubenetes deployment architecture plays a vital role so there’s no down time with having right strategy at place
  • Kubernetes tries to solve the problem among the DevOps team, such as the problem of hybrid cloud based strategy.
  • A very special feature which is the service discovery feature through which developers don’t have to worry about  managing everything themselves.
  • Kubernetes enables companies to solve common problems more quickly and efficiently.

React:

React is an open source sIngle page application developed by facebook and released in 2013. React is a Javascript library for DOM manipulation. It is “V” in MVC paradigm where you can use it as a front end development.React is a component based library , which uses Javascript to build its front end applications. It is easy to understand, can handle complex ui and it is responsive.The data flow in react is one dimensional,that is we can pass data from parent component to child component by props.

Prerequisites:

  • Docker installation:

In this guide, we’ll see how to deploy a React application easily to a Kubernetes cluster.

We’ll be using the local Kubernetes cluster throughout this guide. If the Docker is installed then let’s get started. 

Step 1: Creating a React application

We’ll start with a basic React application created with the create-react-app command.

$ npx create-react-app hello

Result:

  Creating a new React app in C:\Users\pc\Desktop\react\hello.   Installing packages. This might take some minutes.   Installing react, react-dom, and react-scripts…> [email protected] postinstall C:\Users\pc\Desktop\react\hello\node_modules\babel-runtime\node_modules\core-js    >    node -e “try{require(‘./postinstall’)}catch(e){}”> [email protected] postinstall C:\U    Users\pc\Desktop\react\hello\node_modules\core-js    >    node -e “try{require(‘./postinstall’)}catch(e){}”    >    [email protected] postinstall C:\Users\pc\Desktop\react\hello\node_modules\core-js-pure   >     node -e “try{require(‘./postinstall’)}catch(e){}   +     [email protected]   +     [email protected]   +r    [email protected]   Added added 1625 packages from 750 contributors and audited 1629 packages in 
  1. npx-create -react app is a command that will install all the required packages for building single page react applications.
  2. After npx create-react-app we define the name of the application ,here we are using hello
  3. The create react app does not handle any backend stuff or  databases,it just creates a front end structure so we can use it with any suitable backend.
  4. It provides you with a good developer experience and it also helps in optimization of your app.

Step :1 Starting React application

$$ npm start
  1.   Above command start your react application.
  2.   Go to your browser and access the react application at your localhost:3000

Step 2:Optimizing React application:

We need the optimized version of react to deploy to kubernetes.

$ npm  run-script build

This command will create build folder and create the build version in build directory

Result:

> npm  run-script build                 > [email protected] build C:\Users\pc\Desktop\_igetintopc.com_Fix\idlex-1.18\react \hello                 > react-scripts build                 Creating an optimized production build…                 File sizes after gzip:                 40.25 KB  build\static\js\2.d4205dc2.chunk.js                 937 B     build\static\js\main.b56f7c61.chunk.js                 773 B     build\static\js\runtime-main.83c66be5.js                 409 B     build\static\css\main.0202d408.chunk.css                  The project was built assuming it is hosted at the server root.                 You can control this with the homepage field in your package.json.                 For example, add this to build it for GitHub Pages:                   “homepage” : “http://myname.github.io/hello”,

Step 2: Dockerizing the application

For deployment we’ll package our application within a container. Kubernetes supports many different container engines, here we’ll use Docker which is widely used.

For the creation of a  Docker container we’ll make  a dockerfile in our application. This file used to instruct docker how to build images step by step. Dockerfile can contain OS type server name application to use or any command to run inside the container.

Docker file has to be in root folder of your project and named as Dockerfile

Using Node

FROM node:10.4.3WORKDIR /usr/src/app COPY package*.json ./ADD package.json /usr/src/app/package.jsonRUN npm installRUN npm install [email protected] -gCOPY . .EXPOSE 3000 CMD [“npm “,”start”];

Here we’ll be using nginx for the  React application and here is the view of our Dockerfile.You can either use node or nginx as i have shown above in both images.In this tutorial we’ll be using the nginx so here is our Dockerfile view.

Using Nginx

FROM nginx:1.19.0COPY build/ /usr/share/nginx/html
  • The Docker pulls everything from nginx:1.19.0 Dockerfile and it copies the React to the container directory

Now your react app is ready,to build docker image type the below command:

$ docker build -t hello .

Result

Sending build context to Docker daemon  162.7MB         Step 1/2 : FROM nginx:1.17         —> 9beeba249f3e         Step 2/2 : COPY build/ /usr/share/nginx/html         —> Using cache         —> 4fb641a64161`         Successfully built 4fb641a64161         Successfully tagged hello:latest

Step 3: Connection to the Kubernetes cluster

In order to start the Kubernetes cluster on your local machine, open the Docker Desktop application and go to the Kubernetes tab

Check this box to enable Kubernetes support. After enabling , it will take some time in creating your cluster.

We will use docker-for-desktop as a default context to kubernetes cluster

kubectl config use-context docker-for-desktop
> Switch to context “docker-for-desktop”.


Following command will be used to get nodes of the cluster

$ kubectl get nodes


Result:

NAME             STATUS   ROLES    AGE   VERSIONdocker-desktop   Ready    master   33h   v1.16.6-beta.0


Following command will be used to see the cluster information

kubectl cluster-info


Result:

Kubernetes master is running at https://kubernetes.docker.internal:6443KubeDNS is running at https://kubernetes.Docker.internal:6443/api/v1/namespaces/kube-system/services/kube-dns:dns/prox    

Step 4: Uploading the Docker image 

Now we’ll upload the image to docker registry so that we can pull the Docker image from anywhere. 

We will start the docker container with the following command and expose port 5000 using the image hello

docker run -d -p 5000:5000 –restart=always –name hello registry:2

For uploading the  Docker image, use your host name after tag and your port , here hello refers to the host name .

docker tag hello zarakmughal/hello

Now push the image to Docker registry:

docker push zarakmughal/hello
The push refers to repository [localhost:5000/hello]180e471f57a2: Pushed      2f4accd375d9: Pushing                                                      6c7de695ede3: Pushed                                                           [======================================>]  44.81MB/57.56Bffc9b21953f4: Pushing [=========================> ]  35.75MB/69.21MB

Now the application is ready to be deployed on the Kubernetes cluster.

Step 5: Deploying  React application

We will use a yaml file to create deployment and service. The Yaml file contains the description of every Kubernetes object(service, pods, deployment, etc.) The Kubernetes entity makes sure our application will have as many replicas (parallel pods) as we define. Here we can also define the type of Docker image we want to use, what type of ports are used and metadata for our application:

kind: DeploymentapiVersion: apps/v1metadata:  name: hellospec:  replicas: 2  selector:    matchLabels:      app: hello  template:    metadata:      labels:        app: hello    spec:      containers:        – name: hello          image: zarakmughal/hello          imagePullPolicy: Always          ports:            – containerPort: 80      restartPolicy: Always

Just with deployment we wouldn’t be able to access our application . So we’ll use service to expose our application.By using service we can expose the ports to the cluster/outside.

Among several types of kubernetes service,we’ll be using the simplest one,that is nodeport. This type will expose a defined port on every node in our Kubernetes cluster (with the local Kubernetes cluster, we just have one node) and map it to an application’s port:

kind: ServiceapiVersion: v1metadata:  name: hellospec:  type: NodePort  ports:    – port: 80      targetPort: 80      protocol: TCP      nodePort: 31000  selector:    app: hello

We can add both the service and deployment into a single .yaml file. For separation we’ll use  —. Here is an example below to show you the deployment.yaml file. Here is an example of both files

We will use deployment part here

We will use  service part here

Now deploying our application to kubernetes:

kubectl apply -f deployment.yaml

Result:

deployment.apps “hello” createdservice “hello” created

Now checking the running status with below command:

kubectl get pods

Result:

NAME                           READY   STATUS             RESTARTS   AGEhello-bc9d4f9f5-68ck8   0/1     ImagePullBackOff   0          14mhello-bc9d4f9f5-fgcfz   0/1     ImagePullBackOff   0          14m
kubectl get deployment

Result:

NAME           READY   UP-TO-DATE hello   2/2     2            2           39s
kubectl get service

Result:

NAME         TYPE        CLUSTER-IP   EXTERNAL-IP   PORT(S)   AGEkubernetes   ClusterIP   10.96.0.1    <none>        443/TCP   32hhello   NodePort    10.104.172.125   <none>        80:31000/TCP   41m

Once everything is completed, you can visit http://localhost:31000 on your machine.Now your react application has been deployed on kubernetes.

As we have completed deploying and checking react application now we can clean the cluster so it will not take any more resources

kubectl delete service,deployment hello


Result:

service “hello” deleteddeployment.extensions “hello” deleted

TL;DR

  1. React is a Javascript web framework used to develop single page application
  2. Kubernetes is an open source platform for orchestration of containerized application
  3. Kubernetes gives us the flexibility to build and deploy our application without needing to rebuild our container images.
  4. For setting Kubernetes on our local machine we’ll enable Kubernetes from Docker Desktop application.
  5. Kubernetes has the capability to handle huge traffic with replicas of application – pods
  6. Kubernetes cluster has a set of multiple machines which are used for running applications .
  7. By using kubernetes we can solve many problems more efficiently.
  8. For building a Docker container we have made a Dockerfile in the root of the project.
  9. Then we register the image to docker hub to easily pull from anywhere
  10. Then we create deployment and service kubernetes object to deploy application the cluster and expose service to serve traffic
Tags

Related Articles

Check Also
Close
Back to top button
Close
Close