Docker Community Forums

Share and learn in the Docker community.

Running unit test in a .net core WebApi from Dockerfile fails

I am trying to run a unit test in a .net core WebApi.
When i try to create a image out of the solution the unit test fail, but running on IDE unit test works.
I get this error building the image : “Cannot assign requested address (localhost:5000)”
The base URL for Web Api is set as “localhost:5000”.
Below is dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
WORKDIR /app
EXPOSE 80

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY Testing.sln ./
COPY ./Testing/ ./Testing
COPY ./TestProject2/ ./TestProject2

RUN dotnet restore Testing.sln
RUN dotnet test ./TestProject2/TestProject2.csproj

FROM build AS publish
RUN dotnet publish "Testing.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENV ASPNETCORE_URLS=http://+:5000 DOTNET_RUNNING_IN_CONTAINER=true
ENTRYPOINT ["dotnet", "Testing.dll"]

Please, use the </> button to highlight code blocks. I fixed your post so image names are not converted to clickable links making the code less readable.

localhost inside a container is not the same as localhost on the host. When you build an image, every instruction will create a container and every RUN instruction will also start that container to execute the commands. You have to make the API available on an other IP which is available from these containers. Your LAN IP address for example.