Host React app on Nginx in Docker and Kubernetes

Introduction

Today we’ll learn how to host your React Docker app on NGINX inside Docker and Kubernetes We’ll take a sample React app and host it on NGINX web server inside Docker. Then we’ll export the Docker image and import it into Kubernetes. Finally we’ll host this imported docker image in Kubernetes on Ubuntu using microk8s. We’ll also learn how to scale and load balance your app.

As usual, we’ll focus only on Ubuntu Server based terminal commands. No GUI commands. We’ll be using microk8s toolset of Ubuntu. Microk8s is not a subset but a full upstream version of Kubernetes. Microk8s makes it easy for a developer to install Kubernetes on Ubuntu with great default options. It also makes hosting and managing images easier.

Focus

  1. Create sample React app.
  2. Host the React app on NGINX web server inside Docker.
  3. Export the app image from Docker into a file.
  4. Import the docker image file in Kubernetes.
  5. Host the docker app in Kubernetes.

Steps

  1. Install nodejs, npm and default React app.
  2. Create a production build of the React app.
  3. Install docker.
  4. Create a Dockerfile file to create an image of a production build of your React app with NGINX.
  5. Export the docker image into a file.
  6. Install microk8s (Kubernetes).
  7. Enable required services for Kubernetes.
  8. Import the docker image.
  9. Host the app image in Kubernetes.
  10. Scale and load balance your app.

Here we go!

Note: To avoid typing sudo everytime, use sudo -s, and then enter password. But for the sake of completeness, I’ll be prefixing the commands with sudo where ever required.

1. Install nodejs, npm and default React app

sudo apt update
sudo apt upgrade

sudo apt-get install nodejs
sudo apt-get install npm
Install the default React app
npm install -g create-react-app
create-react-app --version
Create the hello world app and check if it is running fine
create-react-app first-react
cd ./first-react
npm start

If the output looks fine, then the first App is running. Press Ctrl-C to exit.

2. Create a production build of the React app

sudo npm run build

This will create a build folder and ill contain a production ready site.

3. Install Docker

sudo apt-get install docker.io
sudo systemctl enable docker
sudo systemctl start docker

4. Create a Dockerfile file to create an image of a production build of your React app with NGINX

Type nano Dockerfile and paste the following contents:

#Based on Node.js, to build and compile the frontend
FROM node as build

WORKDIR /app

COPY package*.json /app/

RUN npm install

COPY ./ /app/

RUN npm run build

# Stage 1, based on Nginx, to have only the compiled app, ready for production with Nginx
FROM nginx

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

Press Ctrl-S and Ctrl-X to exit.

Build your Docker image
docker build -t first-react-app .

You can verify the contents of the image. You can bash into the image and check the contents of the file system.

docker run -it first-react-app bash
Notes about the Dockerfile
  1. You have two FROM statements. The first FROM downloads a node image, builds you React application
  2. The second FROM statement, copies the contents from first image, discards the first image, and builds a new image with NGINX inside it.
  3. The line -from=build /app/build allows you to copy contents from your first image into the second image. The build word after -from= comes from the first line in Dockerfile – as build
  4. You are chaining image building. This is officially called a multi-stage build.
  5. Important note: This new image only has the production ready build of your App that site hosted in NGINX. You don’t need nodejs or npm installed or running inside the image.

5. Export the docker image into a file

docker save first-react-app > first-react-app.tar

This creates a .tar file around 137 MB in size for this scenario.

6. Install microk8s (Kubernetes)

snap install microk8s --classic

This will install microk8s (Kubernetes) in a single command.

Important note: For Kubernetes here you have to prefix all your commands with microk8s before typing kubectl. This can be tedious. To enable you to skip typing microk8s all the time, type:

snap alias microk8s.kubectl kubectl

To revert back, type: snap unalias kubectl

Check which services are enabled/disabled

microk8s status

7. Enable required services for Kubernetes

microk8s enable dns dashboard

8. Import the docker image

microk8s ctr image import first-react-app.tar

Note that this imports the image docker.io namespace – docker.io/library/first-react-app:latest

Check the images installed in current Kubetnetes
microk8s ctr images ls
To check whether our image is imported successfully
microk8s ctr images ls | grep "first-react-app"

9. Host the app image in Kubernetes

Create a .yaml file to create a Kubernetes deployment.

nano deployment.yaml

Paste the following contents inside

apiVersion: apps/v1
kind: Deployment
metadata:
  name: first-react-deployment
  labels:
    app: first-react-app
spec:
  replicas: 5
  selector:
    matchLabels:
      app: first-react-app
  template:
    metadata:
      labels:
        app: first-react-app
    spec:
      containers:
      - name: first-react-app
        image: docker.io/library/first-react-app:latest
        imagePullPolicy: Never
        ports:
        - containerPort: 80

Important note: If you do not specify imagePullPolicy: Never in the .yaml file, it will make your life miserable. Your deployment will not get created since there is a default policy getting applied while pulling the image for deployment. Since you are developing initially and to make things easier, we skipped applying pull policy rules.

10. Scale and load balance your app

As you might have observed, in the .yaml file we had mentioned replicas: 5. This will scale your app to 5 container instances for load balancing.

Pods

Pods in Kubernetes are smallest instance which hosts your container. Technically, a pod can have multiple containers, but for simplicity, we will assume it has only one instance of our running container.

So when you run this command – microk8s kubectl get pods, you’ll get.

NAME                                      READY   STATUS    RESTARTS   AGE
first-react-deployment-5cb789d84f-5jf47   1/1     Running   0          9m42s
first-react-deployment-5cb789d84f-kll6h   1/1     Running   0          9m42s
first-react-deployment-5cb789d84f-qjlv8   1/1     Running   0          9m42s
first-react-deployment-5cb789d84f-s7kgl   1/1     Running   0          9m42s
first-react-deployment-5cb789d84f-sztsd   1/1     Running   0          9m42s

Since we had mentioned 5 replicas, your app is running in 5 different pods. You can also run microk8s kubectl get all

NAME                                          READY   STATUS    RESTARTS   AGE
pod/first-react-deployment-5cb789d84f-5jf47   1/1     Running   0          33m
pod/first-react-deployment-5cb789d84f-kll6h   1/1     Running   0          33m
pod/first-react-deployment-5cb789d84f-qjlv8   1/1     Running   0          33m
pod/first-react-deployment-5cb789d84f-s7kgl   1/1     Running   0          33m
pod/first-react-deployment-5cb789d84f-sztsd   1/1     Running   0          33m

NAME                 TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)   AGE
service/kubernetes   ClusterIP   10.152.183.1   <none>        443/TCP   95m

NAME                                     READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/first-react-deployment   5/5     5            5           33m

NAME                                                DESIRED   CURRENT   READY   AGE
replicaset.apps/first-react-deployment-5cb789d84f   5         5         5       33m

As you can see, out app is still not exposed in the service namespace/section.

To finally expose our deployment, type:
microk8s kubectl expose deployment first-react-deployment --type LoadBalancer --name react-deployment-service --external-ip=192.168.26.133

You have now exposed the service to be usable externally. You can now type – microk8s kubectl get all

NAME                                          READY   STATUS    RESTARTS   AGE
pod/first-react-deployment-5cb789d84f-5jf47   1/1     Running   0          40m
pod/first-react-deployment-5cb789d84f-kll6h   1/1     Running   0          40m
pod/first-react-deployment-5cb789d84f-qjlv8   1/1     Running   0          40m
pod/first-react-deployment-5cb789d84f-s7kgl   1/1     Running   0          40m
pod/first-react-deployment-5cb789d84f-sztsd   1/1     Running   0          40m

NAME                               TYPE           CLUSTER-IP       EXTERNAL-IP      PORT(S)        AGE
service/kubernetes                 ClusterIP      10.152.183.1     <none>           443/TCP        101m
service/react-deployment-service   LoadBalancer   10.152.183.230   192.168.26.133   80:32751/TCP   33s

NAME                                     READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/first-react-deployment   5/5     5            5           40m

NAME                                                DESIRED   CURRENT   READY   AGE
replicaset.apps/first-react-deployment-5cb789d84f   5         5         5       40m

Alternatively you can also type for an exhaustive output.

microk8s kubectl get all --all-namespaces
Inspect a single pod
kubectl describe pod first-react-deployment-5cb789d84f-5jf47

Replace the pod name with your own.

Done!

Hurray! You have finished deploying and exposing your first React App and scaled it to 5 instances. Kubernetes will also load balance it for you automatically.

Check your site by typing the following since this is your Load Balancer IP address and is exposed on port 80.

curl http://10.152.183.230

Check out this line from the output – service/react-deployment-service LoadBalancer 10.152.183.230 192.168.26.133 80:32751/TCP 33s

Since you site is also exposed to external machines on port 32751 on the network, you can type this from an external machine on the network.

curl http://192.168.26.133:32751

Conclusion

Yes! we learnt how to host your React Docker app on NGINX inside Docker and Kubernetes. Hope this helps you. If you have questions you can send them to code@onezeroeight.co

148 Responses

  1. there asmr says:

    What’s Taking place i’m new to this, I stumbled upon this I have discovered It absolutely useful and it has aided me
    out loads. I hope to contribute & help other users like its
    aided me. Good job.

  2. bitly.com says:

    great submit, very informative. I wonder why the opposite experts of this sector do not understand this.
    You must continue your writing. I’m confident, you have a great readers’ base already!
    scoliosis surgery https://0401mm.tumblr.com/ scoliosis surgery

  3. F*ckin’ awesome things here. I am very satisfied to look your article. Thank you a lot and i am taking a look ahead to touch you. Will you kindly drop me a mail?

  4. Needed to post you a very small word to say thanks a lot again regarding the pleasing views you have documented above. This has been so tremendously generous with people like you to convey unreservedly precisely what a few individuals would have offered for an electronic book in making some cash for themselves, certainly since you might have done it in case you desired. Those good ideas also acted to become a easy way to be sure that the rest have a similar interest similar to my very own to understand a good deal more regarding this condition. I am certain there are millions of more pleasant moments up front for those who look over your blog.

  5. I every time used to study article in news papers but now as I am a user of internet so from now I am using net for articles,
    thanks to web. quest bars https://www.iherb.com/search?kw=quest%20bars quest bars

  6. Thanks a bunch for sharing this with all people you really recognise what you are talking about! Bookmarked. Kindly additionally seek advice from my site =). We will have a link trade contract between us!

  7. coub.com says:

    Wonderful blog! I found it while searching on Yahoo
    News. Do you have any tips on how to get listed in Yahoo News?
    I’ve been trying for a while but I never seem to get there!
    Thanks scoliosis surgery https://coub.com/stories/962966-scoliosis-surgery scoliosis surgery

  8. Hello! I just would like to give a huge thumbs up for the great info you have here on this post. I will be coming back to your blog for more soon.

  9. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.

  10. Aw, this was a really nice post. In idea I would like to put in writing like this additionally ? taking time and actual effort to make a very good article? but what can I say? I procrastinate alot and by no means seem to get something done.

  11. Poodle says:

    WONDERFUL Post.thanks for share..more wait .. 😉 ?

  12. I?d have to check with you here. Which is not something I usually do! I enjoy reading a post that will make people think. Also, thanks for allowing me to comment!

  13. Nice post. I learn something more challenging on different blogs everyday. It will always be stimulating to read content from other writers and practice a little something from their store. I?d prefer to use some with the content on my blog whether you don?t mind. Natually I?ll give you a link on your web blog. Thanks for sharing.

  14. you have a great blog here! would you like to make some invite posts on my blog?

  15. very nice post, i certainly love this website, keep on it

  16. Spot on with this write-up, I truly think this website needs much more consideration. I?ll probably be again to read much more, thanks for that info.

  17. It?s hard to find knowledgeable people on this topic, but you sound like you know what you?re talking about! Thanks

  18. shorte says:

    Wow, superb weblog structure! How long have you ever been running a blog for? you make running a blog glance easy. The total glance of your website is fantastic, let alone the content material!!

  19. Excellent article! We are linking to this great content on our website.
    Keep up the great writing.

  20. whoah this weblog is magnificent i love reading your posts. Keep up the good work! You understand, lots of people are looking round for this information, you can aid them greatly.

  21. Thanks for another wonderful article. Where else may
    anyone get that type of information in such a perfect approach of writing?
    I have a presentation subsequent week, and I’m on the look for such information.

  22. Wow, incredible blog structure! How long have you been running a blog for? you made running a blog glance easy. The full glance of your site is great, as well as the content material!!

  23. Wow, incredible blog format! How lengthy have you been blogging for? you make blogging look easy. The entire look of your site is great, let alone the content material hitman

  24. I really appreciate this post. I’ve been looking all over for something similar to this! Thank goodness I found it on Bing. You’ve made my day! Thanks again! soyos

  25. Madelaine says:

    I’m not sure why but this weblog is loading extremely slow for me.
    Is anyone else having this problem or is it a problem
    on my end? I’ll check back later on and see if the problem still exists.

  26. You have a very special competence. Your penning skill levels are really top-notch. Many thanks for writing material online and informing your viewers.

  27. With havin so much content and articles do you ever run into any problems of plagorism or copyright infringement? My website has a lot of exclusive content I’ve either authored myself or outsourced but it seems a lot of it is popping it up all over the web without my agreement. Do you know any methods to help reduce content from being stolen? I’d definitely appreciate it.

  28. Hi, Neat post. There is a problem together with your website in internet explorer, could check this… IE still is the market chief and a large element of folks will pass over your great writing due to this problem.

  29. Great blog you have here but I was curious about if you knew of any message boards that cover the same topics talked about here? I’d really love to be a part of group where I can get opinions from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Thank you!

  30. Great website you have here but I was wanting to know if you knew of any user discussion forums that cover the same topics discussed in this article? I’d really like to be a part of community where I can get suggestions from other knowledgeable people that share the same interest. If you have any recommendations, please let me know. Thank you!

  31. I precisely needed to say thanks all over again. I am not sure the things I would have done without the aspects contributed by you over such a theme. Certainly was a real frightening setting for me, but encountering this specialised mode you solved that took me to jump with contentment. I will be happy for this advice and hope that you realize what an amazing job you happen to be providing training men and women through the use of your websites. I know that you haven’t met any of us.

  32. Mytjx com says:

    Hi there! Do you know if they make any plugins to assist with SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thanks!

  33. Read this says:

    Hi there just wanted to give you a quick heads up. The words in your post seem to be running off the screen in Internet explorer. I’m not sure if this is a format issue or something to do with browser compatibility but I thought I’d post to let you know. The design look great though! Hope you get the problem solved soon. Cheers

  34. Today, while I was at work, my sister stole my iphone and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now broken and she has 83 views. I know this is totally off topic but I had to share it with someone!

  35. Hello there! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting sick and tired of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be awesome if you could point me in the direction of a good platform.

  36. I do agree with all the ideas you’ve presented in your post. They’re really convincing and will definitely work. Still, the posts are very short for beginners. Could you please extend them a little from next time? Thanks for the post.

  37. Thanks for ones marvelous posting! I seriously enjoyed reading it, you could be a great author.I will be sure to bookmark your blog and definitely will come back later in life. I want to encourage you continue your great writing, have a nice morning!

  38. My partner and I stumbled over here different page and thought I should check things out. I like what I see so i am just following you. Look forward to looking over your web page for a second time.

  39. Take pleasure in what you’re writing and the readers will enjoy reading it.

  40. Tags let you categorize your posts into different categories, which can then be searched by readers.

  41. Click here says:

    You are a very smart individual!

  42. Click here says:

    With havin so much written content do you ever run into any issues of plagorism or copyright violation? My site has a lot of completely unique content I’ve either written myself or outsourced but it looks like a lot of it is popping it up all over the web without my authorization. Do you know any methods to help protect against content from being stolen? I’d definitely appreciate it.

  43. Hi there I am so grateful I found your webpage, I really found you by error, while I was browsing on Askjeeve for something else, Nonetheless I am here now and would just like to say thank you for a fantastic post and a all round exciting blog (I also love the theme/design), I dont have time to browse it all at the moment but I have saved it and also included your RSS feeds, so when I have time I will be back to read a great deal more, Please do keep up the superb work.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enter Captcha Here : *

Reload Image