I am trying to dockerize my web API with docker and I have encountered an error MSB1001: Unkown switch. More details can be found in the cmd prompt image
Does anyone know what this means, I’ve tried to follow up on this in GitHub discussions and posts in StackOverflow.
My Dockerfile:
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR C:UsersAlexaOneDriveDesktopSortITApi
# Copy everything
COPY . .
# Restore as distinct layers
RUN dotnet restore "./Api.csproj"
RUN dotnet publish "/Api.csproj" -c release -o ./
# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:6.0
COPY --from=build /Api .
ENTRYPOINT ["dotnet", "Api.dll"]
My file directory
2
Answers
I assume you have build context in the folder with
Api.csproj
file. First – WORKDIR sets the current working directory in the container. It is not a directory on the host system. You start with a directory where you copy source code from the build context to the container. Good name for it /srcNote that in order to optimize the build process and use caching, its better to start with copying *.csproj file only and restore dependencies. Because source code changes more often then dependencies of the application.
Next you want to build/publish your application somewhere in a container. Usually you create new directory for that and don’t use the system root:
And the last step – you should copy the published application to the runtime container. Here you set the current directory to the directory where the published application will be located:
And don’t forget to expose ports used by your API.
Dockerfile:
There are a number of issues with your Dockerfile. The one giving you the ‘unknown switch’ is on the publish statement, where you’ve given the project file name as
/Api.csproj
. It should be./Api.csproj
.As others have pointed out, your WORKDIR uses Windows syntax, but you’re building a Linux image and should use Linux syntax. I like to use
/src
as the directory in my build steps.You publish the project to
./
which means that you’ll end up with a directory that contains both your source and the published project. You want to keep them separate, so you can copy only the published project into the final image.Which those changes, you end up with