首页 > 解决方案 > 带有版本的 dotnet 构建在 docker 中不起作用

问题描述

我正在尝试使用 Docker 构建我的 .net 核心应用程序。我想在 build 覆盖我的应用程序版本。在运行时稍后的某个地方显示它。

我的 Docker 文件如下所示:

FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet tool install -g GitVersion.Tool --version=5.0.0-beta1-72

RUN export PATH="$PATH:/root/.dotnet/tools" && \
    version="$(dotnet gitversion /output json /showvariable NuGetVersion)" && \
    dotnet build --no-restore /property:Version=$version  && \
    dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]

当我在我的 Windows 机器上尝试 RUN 指令中的相同命令时 - 一切正常。我还尝试在 WSL(Ubuntu 18)上运行相同的命令,这也很好——我的构建命令有汇编版本。但我不明白为什么它在 Docker 中不起作用。

我也试图删除我所有的 GitVersion 魔法并使用这个:

FROM microsoft/dotnet:2.2-sdk AS build-env
WORKDIR /src

RUN apt-get update && \
    apt-get install -y libgit2-dev && \
    ln -s /usr/lib/x86_64-linux-gnu/libgit2.so /lib/x86_64-linux-gnu/libgit2-15e1193.so

COPY ..

WORKDIR /src/API

RUN dotnet restore

RUN dotnet build --no-restore /property:Version=1.1.1.0-beta1
RUN dotnet publish --output "/app" --no-build

FROM microsoft/dotnet:2.2-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app .
ENTRYPOINT ["dotnet", "API.dll"]

无论如何,我的结果是一样的。

我使用此代码检查:

public static void Main(string[] args)
{
    Console.WriteLine(typeof(Program).Assembly.GetName());
}

每次我的构建成功但我在 .csproj 文件中定义了没有覆盖的版本。

标签: .netdocker.net-coredockerfilegitversion

解决方案


是的,这应该是一项微不足道的任务,但在我最终能够做到之前,我也遇到了一些问题。花了几个小时解决问题,希望您能节省时间。我建议阅读这篇文章,它有帮助。

我的最终解决方案是使用Docker ARG,您必须在第一个 FROM 之前声明它:

#Declare it at the beginning of the Dockerfile
ARG BUILD_VERSION=1.0.0
...
#Publish your project with "-p:Version=${BUILD_VERSION}" it works also with "dotnet build"
RUN dotnet publish "<xy.csproj>" -c Release -o /app/publish --no-restore -p:Version=${BUILD_VERSION}

需要注意的一件非常重要的事情是:如果您使用多阶段构建(文件中有多个 FROM),则必须在该阶段“重新声明” ARG在这里看到一个类似的问题。

最后,您可以使用以下命令调用您的 Docker 构建:

docker build --build-arg BUILD_VERSION="1.1.1.1"

推荐阅读