通过 GitHub Actions 自动部署 hexo 到 CapRover 的服务器

自动化部署 hexo 到个人服务器上

准备工作

  • 安装 CapRover
    本人使用 CapRover 管理自己的服务器,具体安装教程可参考 使用 CapRover 管理你的服务器
  • 在 CapRover 创建一个blog自定义空白应用
  • 在 GitHub 创建一个仓库,存放博客的代码
  • 本机使用 hexo 创建博客,并关联到 GitHub 上的仓库

编写 workflow

在博客仓库的这个位置编写 workflow

.github/workflow/deploy.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
name: Build & Deploy
# 收到推送代码时触发workflow
on:
push:
branches: ["main"]

jobs:
build-and-deploy:
# 环境
runs-on: ubuntu-latest
# node环境
strategy:
matrix:
node-version: [18.x]

steps:
# 拉取代码,搭建node环境,安装包,运行hexo生成最终文件
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
- run: npm ci
- run: npm run build
# 打包文件
- uses: a7ul/tar-action@v1.1.0
with:
command: c
cwd: "./"
files: |
public/
captain-definition
blog.conf
Dockerfile
outPath: deploy.tar
# 部署到服务器
- name: Deploy App to CapRover
uses: caprover/deploy-from-github@v1.0.1
with:
server: "${{ secrets.CAPROVER_SERVER }}"
app: "${{ secrets.APP_NAME }}"
token: "${{ secrets.APP_TOKEN }}"

编写 CapRover 定义文件

CapRover 官方文档
在博客仓库的根目录下,创建 captain-definition 文件,指定使用dockerfile的方式部署

captain-definition
1
2
3
4
{
"schemaVersion": 2,
"dockerfilePath": "./Dockerfile"
}

编写 dockerfile 文件

在博客仓库的根目录下,创建 Dockerfile 文件。
使用nginx代理博客文件。
注意:Dockerfile 的复制操作,第一层文件夹会自动解包。

Dockerfile
1
2
3
FROM nginx:latest
COPY ./blog.conf /etc/nginx/conf.d/
COPY ./ /var/www/blog

编写 nginx 配置文件

因为使用了 nginx 代理博客,这里写一下 nginx 的配置文件
在博客仓库的根目录下,创建 blog.conf 文件。

blog.conf
1
2
3
4
5
6
7
8
9
10
server {
listen 80;
listen [::]:80;
server_name localhost;

location / {
root /var/www/blog/public;
index index.html;
}
}

设置 GitHub Actions 参数

回看一下我们编写的 workflow 文件,使用了三个参数CAPROVER_SERVERAPP_NAMEAPP_TOKEN,我们需要在 GitHub 上设置一下参数的值。

登录 GitHub,打开博客仓库,点击 Settings,右侧找到Secrets and variables,选择Actions,右边点击添加参数。

  • CAPROVER_SERVER
    你的服务器的 CapRover 的后台的域名,要填完整。eg: https://captain.your-want-name.example.com"
  • APP_NAME
    你的博客在 CapRover 上应用名。eg:blog
  • APP_TOKEN
    你的博客应用的 token,登录你自己的 CapRover,进入你创建博客应用,选择Deployment,找到Enable App Token,点击生成APP_TOKEN,复制到 GitHub 上。

推送代码到 GitHub 仓库

写完博客,将代码 push 到 GitHub 的仓库,进仓库网页,切换Actions标签,观察执行情况。

通过 GitHub Actions 自动部署 hexo 到 CapRover 的服务器

https://blog.feijidui.com/linux-github-actions-hexo-caprover/

作者

Wiley

发布于

2023-02-05

更新于

2024-05-26

许可协议