首页/开发/CI/CD 与发布速查/GitHub Actions 服务容器
工具链要点63 条

GitHub Actions 服务容器

为作业启动伴随服务:数据库、缓存等以 service 容器运行,配合健康检查等待就绪;访问地址按作业是否容器化而不同。

CI/CD 与发布速查开发更新于 2026-10-12
写法jobs.<id>.services.<name>
端口映射为宿主端口
健康检查options 中配置 --health-cmd 等
访问宿主作业用 localhost,容器作业用服务名

Postgres 服务

Postgres 服务
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
        ports: [5432:5432]
        options: >-
          --health-cmd "pg_isready -U postgres"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
    steps:
      - run: PGPASSWORD=test psql -h localhost -U postgres -c 'select 1'
健康检查不充分会出现偶发连接失败:等就绪再跑测试是稳定性关键。

易错点

  • 忘记端口映射:作业访问不到服务
  • 容器化作业仍用 localhost:应使用服务名作为主机

数据来源与参考

  • GitHub Docs《Using containerized services》
​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌