.NET Core控制台应用Docker运行报错:指定命令或文件未找到
Hey, you’re absolutely right about the root cause: the Docker image you built doesn’t contain your application’s DLL file, so dotnet can’t find it when you run the container. Your manual ADD approach works for the two files you listed, but it’s error-prone (you might miss other required files like configuration or dependent DLLs). Let’s go over better, more sustainable solutions:
Option 1: Multi-Stage Build (Recommended)
This approach uses two stages: first to build your project inside a SDK image, then to copy only the published files to a smaller runtime image. It keeps your final image lean and avoids carrying around unnecessary build tools.
Here’s the updated Dockerfile:
# Stage 1: Build the application FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build WORKDIR /src # Copy project file and restore dependencies (caches this step for faster builds) COPY L1_1_Console.csproj . RUN dotnet restore # Copy all source code and publish the app to a dedicated folder COPY . . RUN dotnet publish -c Release -o /app/publish # Stage 2: Run the application using a lightweight runtime image FROM mcr.microsoft.com/dotnet/core/runtime:3.1 LABEL author="somename" LABEL description="some description" WORKDIR /app # Copy only the published files from the build stage COPY --from=build /app/publish . # Set the entry point to run your app ENTRYPOINT ["dotnet", "L1_1_Console.dll"]
Option 2: Copy Local Published Files
If you’ve already run dotnet publish -c Release on your local machine to generate the publish folder, you can skip the build stage entirely and just copy the entire published directory into the runtime image:
FROM mcr.microsoft.com/dotnet/core/runtime:3.1 LABEL author="somename" LABEL description="some description" WORKDIR /app # Copy the entire local publish folder into the container COPY bin/Release/netcoreapp3.1/publish . ENTRYPOINT ["dotnet", "L1_1_Console.dll"]
Why Use the Runtime Image?
The runtime image is much smaller than the sdk image because it only includes the components needed to run .NET Core apps—no compilers or build tools. This makes your final image faster to pull and more secure.
How to Build and Run
- Build the image with:
docker build -t labo1_1_console_image . - Run the container with:
docker run --rm -it labo1_1_console_image
内容的提问来源于stack exchange,提问作者wannes jacobus

