步步驚心:從頭部署服務到 Kubernetes(六)
應用程式部署的最後一哩路:前端靜態檔案的部署
加入前端的 app ,流程基本上一樣,不過有個地方要額外考慮到。前端的 app 是必須被 Kubernetes 外部可以存取到的,而前端要打的 API 也必須是被外部可以存取到的。
假設我們用 Vue 當前端,也就是說 Vue 和前面的 Node.js 應用程式都必須是可以被 Kubernetes 外部存取的。這通常有兩種處理方式,一種是用不同的 domain name,另一種是設定在不同的路徑下,例如前端網站路徑在根目錄 (/) 下,而後端網站路徑在指定路徑下 (例如 /api)。
第一種方式要處理 CORS(跨網域存取)的問題,第二種方式則需要處理 URL 改寫。不過不管用哪一種方式,都要調整 Ingress 設定,在這篇我們將以第二個方式來測試。
設定 Ingress
這次在開發前端程式之前,先來調整 ingress 設定。假設前端程式部署之後使用的 service 名稱為 hellovue,所以修改 ingress.yaml 內容如下,可以看到實際上是建立兩個 ingress:
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: example
annotations:
nginx.ingress.kubernetes.io/rewrite-target: $1
spec:
rules:
- host: hello.node.minikube
http:
paths:
- path: /(.*|$)
backend:
serviceName: hellovue
servicePort: 80
---
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
name: example-api
annotations:
nginx.ingress.kubernetes.io/rewrite-target: $2
spec:
rules:
- host: hello.node.minikube
http:
paths:
- path: /api(/|$)(.*)
backend:
serviceName: hellonode
servicePort: 80
然後部署這個 ingress 並且測試一下新設定的路徑是否能正確取得 hello-node 的 API
$ kubectl apply -f ingress.yaml
$ curl --resolve hello.node.minikube:80:192.168.64.2 http://hello.node.minikube/api
Hello World!
$ curl --resolve hello.node.minikube:80:192.168.64.2 http://hello.node.minikube/api/time
2020/03/08 00:14
看起來不錯,符合預期!
建立 Vue 的前端頁面
Vue 程式的部分簡單列出相關的部分如下:
<template>
<div class="hello">
Now is {{ time }}
</div>
</template><script>
import axios from 'axios'export default {
name: 'HelloVue',
data () {
return {
apiURL: '/api',
time: '',
hello: ''
}
},
created: function () {
this.showtime()
},
methods: {
showtime () {
axios.get(this.apiURL + '/time')
.then((res) => {
this.time = res.data
})
.catch((err) => {
console.log(err)
})
}
}
}
</script>
撰寫 Dockerfile 如下:
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run buildFROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
然後部署到 minikube:
$ docker build -t duanli/hello-vue:0.0.1 .
$ docker push duanli/hello-vue:0.0.1
$ kubectl create deployment hellovue --image=duanli/hello-vue:0.0.1
$ kubectl expose deployment hellovue --port=80 --target-port=80
前端測試的部分要使用瀏覽器了,要記得先在 /etc/hosts 加上設定,例如:
192.168.64.2 hello.node.minikube
到目前已經介紹完部署到 kubernetes 的基本流程,歡迎對於有興趣開發部署於 kubernetes 環境的開發者參與討論。
<<上一篇