# 在容器中运行 CodeQL 代码扫描

可以通过确保所有进程在同一容器中运行，从而在容器中运行 code scanning 。

## 关于 code scanning 与容器化构建

如果你为编译型语言配置 code scanning，并且在容器化环境中构建代码，则分析可能会失败，并显示错误消息“构建期间未看到源代码”。 这表明 CodeQL 无法在编译过程中监控你的代码。

必须在生成代码的容器内运行 CodeQL 。 无论你使用的是 CodeQL CLI 还是 GitHub Actions，这都适用。 有关 CodeQL CLI 的详细信息，请参阅 [在现有 CI 系统上使用代码扫描](/zh/enterprise-server@3.20/code-security/code-scanning/integrating-with-code-scanning/using-code-scanning-with-your-existing-ci-system)。 如果使用 GitHub Actions，请将工作流配置为在同一容器中运行所有操作。 有关详细信息，请参阅[示例工作流](#example-workflow)。

> \[!NOTE]
> CodeQL CLI 当前与非 glibc Linux 发行版不兼容，例如（基于 musl 的）Alpine Linux。

## CodeQLcode scanning 的依赖项

如果使用的容器缺少某些依赖项（例如，必须安装 Git 并将其添加到 PATH 变量），则可能很难运行 code scanning 。 如果遇到依赖问题，请查看 GitHub 的运行器映像上通常包含的软件列表。 有关详细信息，请参阅以下位置中特定于版本的 `readme` 文件：

* Linux：<https://github.com/actions/runner-images/tree/main/images/ubuntu>
* macOS：<https://github.com/actions/runner-images/tree/main/images/macos>
* Windows： <https://github.com/actions/runner-images/tree/main/images/windows>

## 示例工作流

> \[!NOTE]
> 本文介绍了此版 CodeQL 的初始发行版中包含的 CodeQL CLI 操作版本和相关 GitHub Enterprise Server 捆绑包中可用的功能。 如果企业使用较新版本的 CodeQL 操作，请参阅本文的 [GitHub Enterprise Cloud 版本](/zh/enterprise-cloud@latest/code-security/tutorials/customize-code-scanning/run-in-a-container)，了解有关最新功能的信息。
> 有关使用最新版本的信息，请参阅“[为您的设备配置代码扫描](/zh/enterprise-server@3.20/admin/code-security/managing-github-advanced-security-for-your-enterprise/configuring-code-scanning-for-your-appliance#configuring-codeql-analysis-on-a-server-without-internet-access)”。

此示例工作流使用 GitHub Actions 在容器化环境中运行 CodeQL 分析。
`container.image` 的值标识要使用的容器。 在此示例中，映像名为 `codeql-container`，标记为 `f0f91db`。 有关详细信息，请参阅“[GitHub Actions 的工作流语法](/zh/enterprise-server@3.20/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idcontainer)”。

```yaml
name: "CodeQL"

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    - cron: '15 5 * * 3'

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      actions: read

    strategy:
      fail-fast: false
      matrix:
        language: [java-kotlin]

    # Specify the container in which actions will run
    container:
      image: codeql-container:f0f91db

    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
      - name: Initialize CodeQL
        uses: github/codeql-action/init@v4
        with:
          languages: ${{ matrix.language }}
      - name: Build
        run: |
          ./configure
          make
      - name: Perform CodeQL Analysis
        uses: github/codeql-action/analyze@v4
```