Search code examples
c#dockerasp.net-core-webapivisual-studio-2022

Docker - Access to path /root is denied in C# / ASP.NET Core Web API


I have Docker desktop installed on my machine. I have configured dockerfile for C# ASP.NET Core Web API project created in Visual Studio 2022. It was working until I added file access code (appsettings.json) through register services code.

I have full access to project and Docker as admin still I am getting error. Am I missing some setting? Below are some initial and final lines of the docker file and a screenshot of the error.

dockerfile:

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER app
WORKDIR /app
EXPOSE 8080

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
.
.
.
.
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./webapi_project.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "webapi_project.dll"]

Error screenshot:

file denier error


Solution

  • You're running your container as the user app (line 2 in your Dockerfile). That user doesn't have access to the /root directory.

    The reason it tries to access that is that your code looks for appsettings in the parent directory (var basepath = Directory.GetParent(filePath)). Since your app is running in the /app directory, the parent directory is the root directory.

    You then try to find the appsettings.json file by searching in all subdirectories of the root directory. And the app user doesn't have the necessary permissions to do that.

    If your appsettings file is in the /app directory, then I'd suggest not searching from the root directory, but just from the /app directory. Your app user should have access to do that.