打算把个人博客部署在k8s上面,记录下过程。
博客是由vuepress搭建的,本质是个nodejs项目,托管在了github
执行npm run build
后会生成静态资源
- 首先项目根目录添加
Dockerfile
和.dockerignore
Dockerfile
# build stage
FROM node:lts-alpine as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
# production stage
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/docs/.vuepress/dist /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
复制代码
.dockerignore
node_modules
.git
复制代码
- 打包docker镜像并推到docker hub仓库
docker build . --file Dockerfile -t finleyma/blog-vuepres
docker push
复制代码
打开 hub.docker.com/r/finleyma/…
成功啦
- 项目根目录创建kubernates.yaml
注意:我们已经提前在google cloud上建立好了包含3个工作节点的k8s集群
其中Deployment的replicas为3,因为我们的k8s集群有三个工作节点
Service的类型为LoadBalancer,这样google cloud会自动帮我们创建负载均衡器并分配IP
apiVersion: apps/v1
kind: Deployment
metadata:
name: deployment-blog-vuepress
labels:
app: blog-vuepress
spec:
replicas: 3
selector:
matchLabels:
app: blog-vuepress
template:
metadata:
labels:
app: blog-vuepress
spec:
containers:
- name: blog-vuepress
image: finleyma/blog-vuepress:latest
ports:
- containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
name: service-blog-vuepress
spec:
type: LoadBalancer
selector:
app: blog-vuepress
ports:
# 默认情况下,为了方便起见,`targetPort` 被设置为与 `port` 字段相同的值。
- protocol: TCP
## service暴露在cluster ip上的端口
port: 80
## targetPort是pod上的端口,Dockerfile中指定了80
targetPort: 80
复制代码
- 稍等片刻,查看刚刚创建的service
kubectl describe svc service-blog-vuepress
注意LoadBalancer Ingress是暴露出来的可以外部访问的IP啦
以上基本功能已经完成,接下来我们实现自动化
- 提交代码后自动创建镜像
项目根目录创建.github/workflows/cloud.yaml
# This is a basic workflow to help you get started with Actions
name: CI
# Controls when the action will run. Triggers the workflow on push or pull request
# events but only for the master branch
on:
push:
branches: [ master ]
env:
CI: true
NODE: 14.x
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- uses: actions/checkout@v2
- name: Install Node.js
uses: actions/setup-node@v1
with:
node-version: "${{ env.NODE }}"
- name: Install npm dependencies
run: npm ci
- name: Run build task
run: npm run build --if-present
- name: Build the Docker image
run: docker build . --file Dockerfile
- name: publish docker image
uses: elgohr/Publish-Docker-Github-Action@master
with:
name: finleyma/blog-vuepress
username: finleyma
password: ${{ secrets.DOCKER_HUB_PASSWORD }}
tags: "latest"
复制代码
- TODO github actions结合google cloud
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END