---
title: "GitHub Actions 发布容器镜像"
description: "用 GitHub Actions 发布镜像到 GHCR，解释镜像版本与容器重建后的反代行为。"
canonical_url: "https://mhaibaraai.cn/docs/deployment/github-actions"
---
# GitHub Actions 发布容器镜像

> 用 GitHub Actions 发布镜像到 GHCR，解释镜像版本与容器重建后的反代行为。

## 构建并推送 GHCR

```yaml [.github/workflows/deploy.yml]
name: Deploy

on:
  push:
    branches:
      - main

env:
  REGISTRY: ghcr.io
  IMAGE: ghcr.io/${{ github.repository }}

permissions:
  contents: read
  packages: write

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 20

    steps:
      - uses: actions/checkout@v6
      - uses: docker/setup-buildx-action@v4

      - name: Log in to GHCR
        uses: docker/login-action@v4
        with:
          registry: ${{ env.REGISTRY }}
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Build and push Docker image
        uses: docker/build-push-action@v7
        with:
          context: .
          push: true
          tags: |
            ${{ env.IMAGE }}:latest
            ${{ env.IMAGE }}:${{ github.sha }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
```

工作流使用 `GITHUB_TOKEN` 和 `packages: write` 发布镜像。已有 GHCR 包如果报 `permission_denied: write_package`，到包的设置检查仓库关联和 Actions 权限。发布时同时保留提交 SHA 标签，部署和回滚可明确选择具体版本。

构建确实需要凭证时，用 BuildKit secret 挂载。运行时凭证由容器运行环境注入。

## 容器重建时保持 Nginx 可启动

在同一个 Docker 自定义网络里，Nginx 可以通过容器名访问应用。使用 Docker 内置 DNS 和变量形式的上游，让 Nginx 在请求时解析应用容器：

```nginx
location / {
    resolver 127.0.0.11 valid=30s;
    set $upstream app:3000;
    proxy_pass http://$upstream;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-Proto $scheme;
}
```

应用未就绪时请求仍可能返回 `502`。用实际 HTTP 请求确认发布后的应用可用。本文早期方案依赖 Watchtower 自动拉取镜像，其[原仓库](https://github.com/containrrr/watchtower)已归档。

---

- [GitHub 发布容器镜像](https://docs.github.com/en/actions/tutorials/publish-packages/publish-docker-images)
- [Nginx resolver 文档](https://nginx.org/en/docs/http/ngx_http_core_module.html#resolver)


## Sitemap

See the full [sitemap](https://mhaibaraai.cn/sitemap.md) for all pages.
