需求背景

使用 Hugo 生成静态网站,通过多阶段容器构建优化镜像体积,并部署到 Nginx 容器,实现快速发布与版本控制。

实现步骤

  1. Hugo 项目初始化
  • 本地创建 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
  1. 多阶段 Dockerfile 编写
    第一阶段使用 Hugo 镜像构建静态文件,第二阶段使用 Nginx 部署:






    dockerfile







# 构建阶段:生成静态网站
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;"]
  1. Nginx 配置(nginx.conf)
    支持 Hugo 的 pretty URLs(无.html后缀):






    nginx







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;
}
  1. 构建与运行
  • 构建镜像:docker build -t hugo-site:v1 .
  • 运行容器:docker run -d -p 80:80 --name my-hugo-site hugo-site:v1
  • 访问http://localhost验证网站是否正常显示。
  1. CI/CD 集成
  • 在 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

实例 13:Hugo 静态网站容器化构建与部署_Nginx

  • 推送代码后自动触发构建,镜像推送至仓库,可在服务器通过docker pull更新网站。