## 为什么用 GitHub Actions
以前部署静态博客的流程:本地写 Markdown → 运行构建命令 → 生成 HTML → SCP 上传到服务器。每次更新都要手动重复。
GitHub Actions 是 GitHub 提供的免费 CI/CD 服务,公有仓库无限使用,私有仓库每月 2000 分钟。
## 最简单的部署 Workflow
```yaml
name: Deploy Blog
on:
push:
branches: [main]
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm install && npm run build
- name: Deploy to Server
uses: easingthemes/ssh-deploy@v4
with:
SSH_PRIVATE_KEY: ${{ secrets.SSH_KEY }}
REMOTE_HOST: ${{ secrets.SSH_HOST }}
REMOTE_USER: ${{ secrets.SSH_USER }}
TARGET: /var/www/blog
SOURCE: "public/"
```
## 配置 secrets
仓库 Settings → secrets and variables → Actions 中添加:
- `SSH_HOST`:服务器 IP
- `SSH_USER`:SSH 用户名
- `SSH_KEY`:SSH 私钥内容
建议专门为 GitHub Actions 生成一对新密钥。
## 带缓存加速构建
```yaml
- uses: actions/setup-node@v3
with:
node-version: '18'
cache: 'npm'
- uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
```
## Docker 镜像自动构建
```yaml
- name: Build and Push
uses: docker/build-push-action@v4
with:
push: true
tags: username/myapp:latest
```
配置完 GitHub Actions,你只需要专注写作和 push,构建部署全自动。