需求背景
实现步骤
- 本地创建 Hugo 项目(如需测试):
bash
hugo new site hugo-demo
cd hugo-demo
git clone https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke
echo 'theme = "ananke"' >> hugo.toml
hugo new posts/first-post.md
# 构建阶段:生成静态网站
FROM klakegg/hugo:0.115.4-alpine AS builder
WORKDIR /app
# 复制项目文件
COPY . .
# 构建生产版本(禁用草稿)
RUN hugo --minify --environment production# 运行阶段:部署到Nginx
FROM nginx:alpine
# 复制构建产物到Nginx
COPY --from=builder /app/public /usr/share/nginx/html
# 配置Nginx支持Hugo的永久链接(避免刷新404)
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
server {listen 80;root /usr/share/nginx/html;index index.html;# 处理目录请求(如/posts/指向posts/index.html)location / {try_files $uri $uri/ $uri.html /index.html;}# 启用gzip压缩gzip on;gzip_types text/css application/javascript image/svg+xml;
}
- 构建镜像:
docker build -t hugo-site:v1 .
- 运行容器:
docker run -d -p 80:80 --name my-hugo-site hugo-site:v1
- 访问
http://localhost
验证网站是否正常显示。
- 在 Git 仓库添加 GitHub Actions 工作流(
.github/workflows/deploy.yml
):
yaml
name: Deploy Hugo Site
on:push:branches: [ main ]
jobs:build-and-deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v4with:submodules: true # 拉取主题子模块- name: Build Hugo siteuses: klakegg/actions-hugo@v3with:hugo-version: 0.115.4args: --minify- name: Build and push Docker imageuses: docker/build-push-action@v5with:context: .push: truetags: your-registry/hugo-site:latest
- 推送代码后自动触发构建,镜像推送至仓库,可在服务器通过
docker pull
更新网站。