Create a React app in Kubernetes

What is Kubernetes?

Kubernetes (or K8s) is an open-source container orchestration system. It is used for application deployment and scaling. It has become very popular recently, partly due to the rise of cloud-native solutions. It lets you deploy containers to clusters, meaning a network of virtual machines. The basic idea of Kubernetes is to further abstract machines, storage, and networks away from their physical implementation.

When should you use Kubernetes?

Kubernetes is best used in microservice architectures, since it makes it easier to split your application into smaller components with containers that can then be run on different cloud environments, giving you the option to choose the best host for your needs. Kubernetes is built to be used anywhere, so you can deploy to public/private/hybrid clouds, enabling you to reach users where they’re at, with greater availability and security.
Kubernetes is also great for scaling your applications, since it provides all these:

  • Horizontal infrastructure scaling: New servers can be added or removed easily.
  • Auto-scaling: Automatically change the number of running containers, based on CPU utilization or other application-provided metrics.
  • Manual scaling: Manually scale the number of running containers through a command or the interface.
  • Replication controller: The replication controller makes sure your cluster has an equal amount of pods running. If there are too many pods, the replication controller terminates the extra pods. If there are too few, it starts more pods.
  • Health checks and self-healing: Kubernetes can check the health of nodes and containers ensuring your application doesn’t run into any failures. Kubernetes also offers self-healing and auto-replacement so you don’t need to worry about if a container or pod fails.
  • Traffic routing and load balancing: Traffic routing sends requests to the appropriate containers. Kubernetes also comes with built-in load balancers so you can balance resources in order to respond to outages or periods of high traffic.
  • Automated rollouts and rollbacks: Kubernetes handles rollouts for new versions or updates without downtime while monitoring the containers’ health. In case the rollout doesn’t go well, it automatically rolls back.
  • Canary Deployments: Canary deployments enable you to test the new deployment in production in parallel with the previous version.

It also allows for better management of your applications. It has many benefits and a steep learning curve.

Who uses Kubernetes?

Kubernetes is used by many companies, like adidas, spotify, cern and many more. You can see the full list of Kubernetes’ case studies here.

When you shouldn’t use it

You shouldn’t use Kubernetes for simple, lightweight applications, since it wouldn’t be really useful for you.
For comparison, this is how deploying a simple app on Kubernetes looks like:

We’re gonna do it anyway and create a React app, to learn the basics of Kubernetes.

A React app in Kubernetes

1. Create a react app

First, we need to create a React app. The easiest way of doing this is with create-react-app

npx create-react-app my-app

If you don’t want to create your own react app and config files, you can use this repository I created for this post.

2. Dockerize the app

In order to deploy the React app to Kubernetes, we need to put it inside a container. Docker is currently the most used container engine.

This is the dockerfile I used. This just copies the React production build to the container.

To speed things up, add .dockerignore to your project and exclude node_modules

Then we run this command to create a docker image:

docker build -t my-react-app .

3. Connect to a Kubernetes cluster

Open your Docker Desktop preferences and switch to your Kubernetes tab. Enable Kubernetes support here. It automatically creates a cluster for you.

Once it is running, connect to it with kubectl

kubectl config use-context docker-for-desktop

4. Upload the Docker image to your container registry

To be able to pull the Docker image within the Kubernetes cluster, we need to upload the image to a Docker registry. We’re deploying the app into a local cluster, so we need a local registry.

You can create one with this command:

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

To upload our Docker image, we have to tag it with the hostname and port of our registry:

docker tag my-react-app localhost:5000/my-react-app

And then we push the image to our Docker registry:

docker push localhost:5000/my-react-app

5. Deploy the React application

For deploying the React application to Kubernetes we need a deployment file. This makes sure our application will have as many replicas as we define. In addition, we can define the Docker image we want to use, what ports are used and further metadata for our application

With just the deployment we wouldn’t be able to access our application from outside. To expose applications, Kubernetes offers a service. Using a service we can define which ports to expose to the cluster/outside.

You can now use this file to deploy your application to Kubernetes with:

kubectl apply -f deployment.yaml

kubectl apply -f service.yaml

You can then check if everything’s running using:

kubectl get pods kubectl get deployment kubectl get service

If everything went right, you should be able to go to http://localhost:31000 and see your react app, now served from a Kubernetes cluster

Summary

Kubernetes is a hard to learn but powerful tool for automating deployment, scaling, and management of containerized applications, especially when you’re using microservices. It is used by many big companies and helps you scale your app without increasing your ops team.

References

  1. https://dev.to/rieckpil/deploy-a-react-application-to-kubernetes-in-5-easy-steps-516j
  2. https://github.com/Koala42/cra-kubernetes
  3. https://kubernetes.io/case-studies/
  4. https://kubernetes.io/docs/tasks/tools/install-kubectl/
  5. https://github.com/facebook/create-react-app#creating-an-app
  6. https://docs.docker.com/
  7. https://devspace.cloud/blog/2019/03/07/deploy-react-js-to-kubernetes
  8. https://www.jeffgeerling.com/blog/2018/deploying-react-single-page-web-app-kubernetes
Learn More

Publishing your Progressive Web Application

Why is this worth your time?

A Progressive web app is quite a new technology not many users know about yet. Publishing to a Play Store will make your app get a lot more installs. Publishing a PWA to the play store is really easy using Google’s Trusted Web Activities.

What is a Trusted Web Activity?

In Google’s words, Trusted Web Activities are a new way to integrate your web-app content such as your PWA with your Android app using a protocol based on Custom Tabs.

A Trusted Web Activity runs a Chrome browser full screen in an Android app, there is no browser UI visible in the app, including the URL bar. This is a powerful capability, therefore it needs to be confirmed it’s made by the same developer – hence ‘Trusted’. To verify the app and the site opened in the TWA belong to the same developer, Digital Asset Links are used to certify ownership.

Native, Trusted Web Activity, WebView or just a PWA?

You might be confused as to what’s the best approach to creating a mobile App. As with almost anything, this largely depends on your use case. Here are some pros and cons of each of the approaches

  • Native – This approach works best if you want your app to be very performant. But it also requires you to have a different codebase in a different language for each platform, multiplying cost and time requirements.
  • Progressive Web App – This is the easiest one, especially when you use create-react-app or PWA builder. The only downside is that not many users know about PWAs yet since it is quite a new technology and your app will never get as big of a traction as it would get on a store.
  • Trusted Web Activity – This requires the web app to be created by you, and you still have to meet the store guidelines. Requires just one codebase, but this doesn’t work on iOS.
  • WebView – Using WebViews is really not worth it anymore – there’s many downsides to them compared to Trusted Web Activities. The only time it would make sense using it is when the content you want to display is not yours. But for that, you’d probably prefer using Chrome Custom Tabs.

Wrapping the PWA inside a Trusted Web Application

  • After you’ve got your PWA built and want to wrap it inside a native app, you first need to clone this repository.
  • After you’ve done this, open the folder you cloned the repository into with Android Studio.
  • Next, open app/build.gradle file. This is how it should look like:

Inside twaManifest, you need to update these three lines:

  • applicationId: change this to your application id.
  • hostname: change this to the url of your website. The website has to be HTTPS, but don’t put the https:// in the string.
  • name: change this to the name of your app

Everything else is optional and depends on your needs.

Now you can try to run your app inside an emulator or with a real device. After you run the app for the first time, it should work even when you’re offline.

Publishing to the Play Store

Now that we’ve done all of the above, we’re ready to publish our app to the Play Store.

  • First, we need to build an apk, we do that by going into Android studio and going to Build > Generate signed Bundle / APK
  • Generate a keystore if you haven’t already. You can generate it directly from android studio keystore generator
  • Now, we need to extract the SHA256 fingerprint from the keystore, we can do that with this command:keytool -list -v -keystore path-to-keystore -alias twa -storepass your-password -keypass your-password
  • Now we set up a Digital Asset Link, we can do that with this tool.
  • Create a .well-known/assetlinks.json file and paste the output from the Digital Asset Link generator.
  • Log in to your Google Play Console and create a new app
  • Go to App releases > Production track > Create release and upload your apk.

Summary

There are four main ways you can make your app downloadable on Android. The best one is creating a PWA and then wrapping it with a Trusted Web Activity. This unfortunately doesn’t work on iOS at all, and iOS is not really PWA friendly when it comes to the homescreen. Right now, the best way to create an iOS app is using webviews or creating a native app.

Learn More

Using WebAssembly in your ReactJS App

What is WebAssembly?

WebAssembly (abbreviated Wasm) is a binary instruction format for a stack-based virtual machine. Wasm is designed as a portable target for compilation of high-level languages like C/C++/Rust, enabling deployment on the web for client and server applications.

Alongside HTML, CSS and Javascript, it is the fourth language to run natively in browsers and supports the 4 major browser engines – Firefox, Chrome, Safari and Edge.

WebAssembly allows you to run code at native speed that is able to work with the JavaScript context and access browser functionality through the same Web APIs accessible from JavaScript. It basically allows you to run your code in native speed inside a browser.
You can learn more in-depth information about WebAssembly here:

(more…)

Learn More

Build a PWA app with React.js

What is a Progressive Web App (PWA)?

So, what is a PWA? On the internet, you can find many definitions for PWAs, but to be considered a Progressive Web App, your app must be (as defined by Google):

  • Reliable – Load instantly and never show the “downasaur”, even in uncertain network conditions.
  • Fast – Respond quickly to user interactions with silky smooth animations and no janky scrolling.
  • Engaging – Feel like a natural app on the device, with an immersive user experience.

(more…)

Learn More

Is It a Koala? Artificial Intelligence in Javascript and TensorFlow.js

AI in your Browser

Tensorflow.js brings machine learning and its possibilities to JavaScript. It is an open source library built to create, train, and run machine learning models in the browser and Node.js

Training and building complex models can take a considerable amount of resources and time. Some models require massive amounts of data to provide acceptable accuracy. And, if computationally intensive, may require hours or days of training to complete. All that taken into consideration, you may not find the browser to be the ideal environment for building such models.

A more appealing use case is importing and running existing models. Depending on the problem you are trying to solve, there might be a model already trained with a data set and for a specific purpose which you can use and import in your code. (more…)

Learn More