docker-为测试结果编写不挂载文件夹

docker-compose not mounting folder for test results

在 运行 作为构建 docker-compose 文件的一部分的单元测试之后,在容器中创建的文件未显示在我的本地文件系统中。

我有以下 Dockerfile:

# IDM.Test/Dockerfile
FROM microsoft/aspnetcore-build:2.0
WORKDIR /src

# Variables
ENV RESTORE_POLICY --no-restore
ENV IGNORE_WARNINGS -nowarn:msb3202,nu1503

# Restore
COPY IDM.sln ./

# Copying and restoring other projects...

COPY IDM.Test/IDM.Test.csproj IDM.Test/
RUN dotnet restore IDM.Test/IDM.Test.csproj $IGNORE_WARNINGS

# Copy
COPY . .

# Test
RUN dotnet test IDM.Test/IDM.Test.csproj -l "trx;LogFileName=test-results.xml"
RUN ls -alR

当运行 RUN ls -alR 我可以看到文件/src/IDM.Test/TestResults/test-results.xml 是在容器中生成的。到目前为止一切顺利。

我正在使用 docker-compose -f docker-compose.test.yml build 开始构建。 docker-compose 看起来像这样:

version: '3'

services:
  idm.webapi:
    image: idmwebapi
    build:
      context: .
      dockerfile: IDM.Test/Dockerfile
    volumes:
      - ./IDM.Test/TestResults:/IDM.Test/TestResults/

我已经在本地创建了文件夹 IDM.Test/TestResults,但是 运行 docker-compose 构建命令成功后没有任何显示。

有什么线索吗?

也许有了这个解释我们可以解决它。让我一步步说一些显而易见的事情以避免混淆。容器创建有两个步骤:

  1. docker build / docker-compose build -> 创建镜像
  2. docker 运行 / docker 组合 / docker-组合 运行 -> 创建容器

卷在第二步中创建(容器创建),而您的命令dotnet test IDM.Test/IDM.Test.csproj -l "trx;LogFileName=test-results.xml"在第一步中执行(图像创建).

If you creates a folder inside container in the same path where you've mounted volume, data in this new folder will only be available locally inside container.

最终,我的推荐可以从以下几点恢复:

  • 检查安装卷的目标文件夹是否未在构建阶段创建,因此未在您的 Dockerfile 中定义任何 RUN mkdir /IDM.Test/TestResults/
  • 另一个小建议不是强制性的,但我喜欢在 docker-compose 文件中定义具有绝对路径的卷。
  • 不要在 Dockerfile 中执行生成您想要的数据的命令,除非您将此命令指定为 ENTRYPOINT 或 CMD,而不是 运行。
  • 在 Dockerfile 中,ENTRYPOINT 或 CMD(或命令:在 docker-compose 中)指定容器启动时在 buildind 之后执行的命令。

尝试使用此 Dockerfile:

# IDM.Test/Dockerfile
FROM microsoft/aspnetcore-build:2.0
WORKDIR /src

# Variables
ENV RESTORE_POLICY --no-restore
ENV IGNORE_WARNINGS -nowarn:msb3202,nu1503

# Restore
COPY IDM.sln ./

# Copying and restoring other projects...

COPY IDM.Test/IDM.Test.csproj IDM.Test/
RUN dotnet restore IDM.Test/IDM.Test.csproj $IGNORE_WARNINGS

# Copy
COPY . .

# Test
CMD dotnet test IDM.Test/IDM.Test.csproj -l "trx;LogFileName=test-results.xml"

或者这个 docker-撰写: 版本:'3'

services:
  idm.webapi:
    image: idmwebapi
    build:
      context: .
      dockerfile: IDM.Test/Dockerfile
    volumes:
      - ./IDM.Test/TestResults:/IDM.Test/TestResults/
    command: >
      dotnet test IDM.Test/IDM.Test.csproj -l "trx;LogFileName=test-results.xml"

创建容器后,您可以检查ls您生成的文件。