K8s deploys a front-end full stack project based on VUE and Node.js

preface

By the time you follow these steps, you have built a full-stack project using Node.js and Vue and understand the fundamentals of K8S. K8s 中文文档:

K8s deployment basics

The basic principle of

  • Create Deployment using YAML
  • K8s Deployment resource creation process:
    1. The user creates Deployment through kubectl.
  • (kubectl create -f nginx-deployment.yaml –record,–record can record which commands have been executed for the current version of Deployment.)
    1. Deployment Creates ReplicaSet.
    1. ReplicaSet creates pods.

The Deployment object, as the name implies, is the object used to deploy the application. It is one of the most commonly used objects in Kubernetes. It provides a declarative definition method for ReplicaSet and Pod creation. This eliminates the need to manually create ReplicaSet and Pod objects as in the previous two articles (use Deployment instead of creating ReplicaSet directly because Deployment objects have many features that ReplicaSet does not have, such as rolling upgrades and rollbacks).

ReplicaSet ensures that the number of pods in the system is always the same as the specified number through “controller mode.”

Deployment also operates the number and properties of ReplicaSet through the controller mode, and then realizes the realization of two scheduling actions of “horizontal expansion/contraction” and “rolling update”

The front end writes the front Deployment through YAML, and then generates the front POD

Then write the front-end Deployment through YAML and generate the ingress,

Ingress acts as a load balancer and is k8S ‘abstraction of a reverse proxy. And it does work roughly like Nginx, The Ingress Controller listens to the Ingress API and translates it into Nginx configuration (Kubernetes declarative API and control loop). It then provides services externally.

Overall Deployment Process

Preparations before setting up an image

  1. Download and install Docker
  2. Configure the Docker address

Af.***** com.cn (provides the image address for the company), docker needs to switch to the Linux environment to run

Set up front-end service images and deploy them

Setting up a Front-end Image

Creating a Basic image

  1. Create the pmsc-frontend-base folder (the folder name is customized).
  2. Create dockerfile in pmsc-frontend-base (dockerfile is fixed name)
  3. Edit the dockerFile file
FROM node:14.16. 0-alpine MAINTAINER User name User name @***.com SHELL ["/bin/sh"."-c"]

RUN echo 'Folder name image build' && \
    sed -i 's/dl-cdn.alpinelinux.org/mirrors.******.com.cn/g' /etc/apk/repositories && \
    apk add git && apk add nginx && \
    sed -i 's/nginx; /root; /g' /etc/nginx/nginx.conf && \
    mkdir -p /run/nginx && \
    mkdir -p /root/repos && \
    cd /root/repos/ && \
    echo 'git clone repos'&&\ git clone project git echo'set npm registry' && \
    npm config set registry http://af.****.com.cn/artifactory/api/npm/npm-down/ && \
    echo 'npm install' && \
    cd ~/repos/Branch name / &&npm i&&echo'clean' && \
    cd ~/ && rm -rf ./repos/ && \
    echo 'done! '
Copy the code
  • Echo ” is the comment content, which can be customized
  • Sed -i ‘s/dl-cdn.alpinelinux.org/mirrors. * * * * *. Com. Cn/g’/etc/apk/repositories will switch repositories is the source of the company
  • Apk add git &&apk add nginx Install git packages and nginx packages
  • sed -i ‘s/nginx; /root; /g’ /etc/nginx/nginx.conf add nginx to nginx.conf; Replace the root;
  • Mkdir -p /run/nginx Creates an nginx directory
  • Mkdir -p /root/repos Creates the repos directory
  • CD /root/repos/ Switch to the repos directory
  • Git Clone Project Git address cloning project
  • NPM config set registry http://af. * * * * *. Com. Cn/artifactory/API/NPM/NPM – down/use NPM source
  • CD ~/repos/ Branch name/Go to the branch folder
  • NPM I download dependencies
  • Rm -rf./repos/ Delete the repos folder

Add git and nginx to the project NPM cache.

eg:

FROM node:14.16. 0-alpine

MAINTAINER  **** ****@qq.com.cn

SHELL ["/bin/sh"."-c"]

RUN echo 'docker-cusmanage-base image build' && \
    sed -i 's/dl-cdn.alpinelinux.org/mirrors.*****.com.cn/g' /etc/apk/repositories && \
    apk add git && apk add nginx && \
    sed -i 's/nginx; /root; /g' /etc/nginx/nginx.conf && \
    mkdir -p /run/nginx && \
    mkdir -p /root/repos && \
    cd /root/repos/ && \
    echo 'git clone repos' && \
    git clone http://iris.*****.com.cn/*****/docker-cusmanage.git && \
    echo 'set npm registry' && \
    npm config set registry http://af.****.com.cn/artifactory/api/npm/npm-down/ && \
    echo 'npm install' && \
    cd ~/repos/docker-cusmanage/ && npm i && \
    echo 'clean' && \
    cd ~/ && rm -rf ./repos/ && \
    echo 'done! '
Copy the code

Uploading a Basic Image

  1. Switch to the current dockerfile directory
cd dockerfiles
cd pmsc-frontend-base
Copy the code
  1. Compile image packaging
Docker build -t mirror address/PMSC frontend - base: * * * - * * * * * * * * * *. - no - cache/ / * * * - * * * * * * * * * * version number time eg: 0.0.1 PMSC frontend - prod and components
Copy the code
  1. Mirror the login
Docker Login Image address// The company needs to provide the login account and password
Copy the code
  1. Image upload
Docker push mirror address/PMSC frontend - base: * * * - * * * * * * * * * *Copy the code
  1. Viewing an Uploaded Image
docker images
Copy the code

Creating a Running Image

  1. Create the pmsc-frontend-prod folder (folder name is optional).
  2. Create dockerfile in the pmsc-frontend-prod folder.
  3. Edit nginx. Conf

Create a files folder in the pmsc-frontend-prod folder and then create the nginx.conf file

Nginx. conf to configure the routing address of the project, so that different projects can enter different main interface

# This is a default site configuration which will simply return 404, preventing    
# chance access to any other virtualhost.                                          
                                                                                   
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        # Everything is a 404Location ~ initial routing address (? <path>/.*)? {root /root/repos/ address of the front-end package file; add_header Cache-Control no-cache; try_files $path /index.html =404;
        }
        # You may need this to prevent return 404 recursion.
        location = /404.html { internal; }}Copy the code

eg:

# This is a default site configuration which will simply return 404, preventing    
# chance access to any other virtualhost.                                          
                                                                                   
server {
        listen 80 default_server;
        listen [::]:80 default_server;
        # Everything is a 404
        

        location ~ /custom(? 
      
       /
      . *)? { root /root/repos/docker-cusmanage/dist; add_header Cache-Control no-cache; try_files $path /index.html =404;
        }
        # You may need this to prevent return 404 recursion.
        location = /404.html { internal; }}Copy the code
  1. Edit dockerfile
FROM image address/Basic image name MAINTAINER user name Username@*****. Com. Cn COPY files/nginx.conf (address of the configured nginx.conf) /etc/nginx/conf.d/default.conf

SHELL ["/bin/sh"."-c"]

ENV BRANCH dev // Custom branch

RUN echo 'Folder name image build' && \
    mkdir -p /root/repos && \
    cd /root/repos/ && \
    echo 'git clone repos'&&\ git clone project location &&\ echo'checkout branch' && \
    cd ~/repos/Git checkout $BRANCH && \ echo'npm install' && \
    cd ~/repos/Branch name / &&npm i&&echo'npm build' && \
    cd ~/repos/Branch name / && NPM run build && \ echo'clean node_modules' && \
    cd ~/repos/Branch name / && rm -rf node_modules && echo build done! CMD nginx -g'daemon off; '

Copy the code

eg:

FROM af.****.com.cn/docker-pbg-local/custom-manage-frontend-base:0.02.

MAINTAINER  **** ****.com.cn

COPY files/nginx.conf /etc/nginx/conf.d/default.conf

SHELL ["/bin/sh"."-c"]

ENV BRANCH master

RUN echo 'docker-cusmanage-frontend image build' && \
    mkdir -p /root/repos && \
    cd /root/repos/ && \
    echo 'git clone repos' && \
    git clone http://iris.****.com.cn/*****/docker-cusmanage.git && \
    echo 'checkout branch' && \
    cd ~/repos/docker-cusmanage/ && git checkout $BRANCH && \
    echo 'npm install' && \
    cd ~/repos/docker-cusmanage/ && npm i && \
    echo 'npm build' && \
    cd ~/repos/docker-cusmanage/ && npm run build && \
    echo 'clean node_modules' && \
    cd ~/repos/docker-cusmanage/ && rm -rf node_modules && \
    echo build done!

CMD nginx -g 'daemon off; '
Copy the code

Uploading a Running Image

  1. Switch to the current dockerfile directory
cd dockerfiles
cd pmsc-frontend-prod
Copy the code
  1. Compile image packaging
Docker build -t mirror address/PMSC frontend - prod: * * * - * * * * * * * * * *. - no - cache// ***-********** Version time eg: 1.0.1-20210604151866 PMs-frontend -prod is related to the component name
Copy the code
  1. Mirror the login
Docker Login Image address// The company provides the account password
Copy the code
  1. Image upload
Docker push mirror address/PMSC frontend - prod: * * * - * * * * * * * * * *Copy the code
  1. Viewing an Uploaded Image
docker images
Copy the code
  1. Image run (local view use)
docker run -p 8088:80-it --rm Image address/PKMSC -frontend-prod:***-**********Copy the code

Complete configuration file directory

The Charts backend is provided, and K8S is deployed and used

Note: If the project adds a large number of new dependencies, you can rebuild the base image to speed up the operation

Deploying front-end Mirroring

Chart file writing

Basic structure Directory

eg:

1. In cus- Fronted, it is mainly front-end Deployment

The front-end POD name is defined in chart.yaml

apiVersion: v2
name: custom-manage-frontend
version: 0.01.
Copy the code

Information about getting the mirror address is defined in deployment.yaml

apiVersion: apps/v1
kind: Deployment
metadata: name: {{.chart.name}} # Deploymentspec:
  replicas: 1# pod replicationsselector: # POD selector definitionmatchLabels: app: {{.chart.name}} # POD selector tagtemplate: metadata: labels: app: {{.chart.name}} # POD label definitionspecContainers: - name: {{.chart.name}} # Container nameimage: af.****.com.cn/docker-pbg-local/pmsc-frontend-prod:0.0. 0# mirror addressimagePullPolicy: Always
          ports:
            - containerPort: 80
              protocol: TCP
Copy the code

The service. Yaml file defines the front-end throw service port number

kind: Service
apiVersion: v1
metadata: name: {{.chart.name}} #spec:
  type: NodePort
  ports:
    - name: {{ .Chart.Name }}
      port: 80
      targetPort: 80
      nodePort: 31456
  selector:
    app: {{ .Chart.Name }}
Copy the code

A front-end Deployment is created as a whole, generating the corresponding POD

2. Cus – Ingress, mainly the Deployment of ingress

The ingress name is defined in chart.yaml

apiVersion: v2
name: custom-manage-ingress
version: 0.01.
Copy the code

Ingress. yaml defines access to different pods through different paths

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: {{ .Chart.Name }}
spec:
  tls:
  - hosts:
    - ismspark.*****.com
    secretName: {{ .Chart.Name }}-tls
  rules:
  - http:
      paths:
      - path: /users
        backend:
          serviceName: nodeapp-svc  // The backend provides services
          servicePort: 3000  // The backend provides services
      - path: /api
        backend:
          serviceName: nodeapp-svc
          servicePort: 3000
      - path: /custom
        backend:
          serviceName: cus-frontend
          servicePort: 80
Copy the code

The/webAPI part is provided by the backend definition, the front-end path is different, to determine whether to enter the front-end interface or back-end request

When our Echart file is ready, upload it to the corresponding server

Basic steps for deploying the front-end image remote server

1. Install FinalShell and FinalShell network management software

2. After installation, add the corresponding SSH connection to the remote server (k8S has been deployed on this server. For details about K8S deployment, refer to k8S official website)

Upload our chart file to the remote server, then replace the image name of the uploaded image directly with the image name under the YAML file, and execute the following command on the console to deploy the ingress and the front-end image to deploy the ingress

helm delete --purge cus-ingress   // For non-initial deployment of the ingress, delete the previous podHelm install --name cus- Ingress/K8S /charts/ CUS - Ingress # Run helm install --name cus- Ingress/K8S /charts/ CUS - Ingress -- Namespace node-kube-appsCopy the code

Note: Helm is the Kubernetes package manager. The command varies with different versions. For details, run Helm help to view the deployed front-end image

helm delete --purge cus-frontend   // For non-initial deployment images, delete the previous podHelm install --name cus-frontend/k8S /charts/ CUS -frontend Run helm install --name cus-frontend/K8S /charts/ CUS -frontend --namespace node-kube-appsCopy the code

After the deployment is complete, you can enter the value

helm list  
Copy the code

View deployed Pods

Set up back-end node service images and deploy them

Create dockerfile

Create a Dockerfile in the app.js layer under our Node backend service file

Compile the following in dockerfile

# mirror version FROM node:8-alpine # claim author MAINTAINER Hapiman # Create a folder in the image RUN mkdir -p /home/service # Use this folder as a working directory WORKDIR /home/service # /home/Service # Use the RUN command to RUN the NPM install library RUN NPM install #3000# NPM start start Node project CMD"npm"."start" ]
Copy the code

To make the mirror

cd manage-api
docker build -t af.*****.com.cn/docker-pbg-local/custom-manage-api:20210709163055Docker run -p docker run -p8088:3000 af.*****.com.cn/docker-pbg-local/custom-manage-api:20210709163055# Test your image without any problems, if any results will be displayed'> [email protected] start /home/service > node./bin/ WWW Successfully started! `Create an image in your Docker repository, then perform the following operations: My address is: Docker login af.***** com.cn # login, Enter your account and password docker push af.*****.com.cn/docker-pbg-local/custom-manage-api:20210709163055# push mirrorCopy the code

The deployment of the mirror

Create a namespace

On the server to be deployed, create node-kube-apps.yaml and a namespace corresponding to node-kube-apps

apiVersion: v1
kind: Namespace
metadata:
   name: node-kube-apps
   labels:
     name: node-kube-apps
Copy the code

Create a pod. Service

On the server to be deployed, create nodeapp.yaml and create the corresponding pod.Service

nodeapp.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nodeapp-deploy
  namespace: node-kube-apps
  labels:
    k8s-app: nodeappk8s
spec:
  dnsPolicy: Default
  replicas: 1
  selector:
   matchLabels:
     k8s-app: nodeappk8s
  template:
    metadata:
      labels:
        k8s-app: nodeappk8s
    spec:
      containers:
      - image: af.****.com.cn/docker-pbg-local/custom-manage-api:20210709163055
        imagePullPolicy: Always        
        name: nodeappk8s        

 
---
apiVersion: v1
kind: Service
metadata:
  name: nodeapp-svc
  namespace: node-kube-apps
  labels:
    k8s-app: nodeappk8s
spec:
  type: NodePort
  ports:
    - port: 3000
      targetPort: 3000
      nodePort: 32000
  selector:
    k8s-app: nodeappk8s
Copy the code

Change image to the image we just uploaded

image: af.*****.com.cn/docker-pbg-local/custom-manage-api:20210709163055

Deploying to the server

Kubectl apply -f nodeapp.yaml #"nodeapp-deploy" created 
# service "nodeapp-svc" created 
Copy the code

Viewing deployment Status

kubectl get svc -n node-kube-apps / / check the SVC
# nodeapp-svc    NodePort   10.10312.208.   <none>        3000:32000/TCP   4d17h
kubectl get pods -n node-kube-apps  / / check the pods
# nodeapp-deploy-647f97d8f6-hjgrz   1/1     Running   5          4d17h
kubectl get deployments -n node-kube-apps / / check deployments
# nodeapp-deploy   1/1     1            1           4d17h
kubectl describe pod -n node-kube-apps nodeapp-deploy-647f97d8f6-hjgrz   // View the pod operation details
kubectl logs -f -n node-kube-apps nodeapp-deploy-647f97d8f6-hjgrz // View log print
Copy the code

If the back-end image service is successfully deployed, the following information is displayed

If the current backend is deployed, go tohttp://ip:30002/custom You can view services. The IP address is the remote service IP address.

References:

Use Kubernetes to deploy the Nodejs Http service

Kubernetes Chinese community

ingress

Helm tutorial