我无法从docker容器上运行的ASP.NET Core Web API app访问主机上的CSV文件。 Web应用程序根据official document中的Dockerfile
在 Release模式下工作。这是我的Dockerfile
和docker-compose.yml
aspnetapp
|- MyApp
| |- MyApp.csproj
|- Dockerfile
|- data
| |- user_input.csv (I want to access here from .NET App on docker)
...
Docker文件
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install -y nodejs
FROM mcr.microsoft.com/dotnet/core/sdk:3.1-buster AS build
WORKDIR /src
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash -
RUN apt-get install -y nodejs
COPY ["MyApp/MyApp.csproj", "MyApp/"]
RUN dotnet restore "MyApp/MyApp.csproj"
COPY . .
WORKDIR "/src/MyApp"
RUN dotnet build "MyApp.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "MyApp.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "MyApp.dll"]
docker-compose.yml
version: "3"
services:
aspnetapp:
image: aspnetapp-img
build: ./aspnetapp
container_name: aspnetapp-ctr
environment:
ConnectionStrings__DefaultConnection: "server=mysql; uid=root; pwd=P@ssw0rd!; database=mydb;"
ports:
- "5000:80"
depends_on:
- mysql
mysql:
image: mysql-img
...
(MyApp还在docker上使用mysql,但我省略了这一部分,因为它与这个问题无关)
要从MyApp容器访问主机(
user_input.csv
)上的CSV文件,我假设我应该将aspnetapp/data
挂载到aspnetapp-img
上的某个位置。如果运行容器时用户更改了CSV文件,则应用应访问新文件,因此我需要在Dockerfile中挂载它而不是COPY
。这是我提出问题的地方。
[ApiController]
[Route("api/[controller]")]
public class FileController : ControllerBase
{
public IActionResult AccessCsvFile()
{
var filePath = Path.Combine(_appEnvironment.ContentRootPath, "user_input.csv");
...
我可以通过这种方式从 Controller 访问csv文件吗?
最佳答案
多种选择:
docker run -v <relative/absolute path/data/user_input.csv>:/data/input.csv
volumes:
- <relative/absolute path/data/user_input.csv>:/data/input.csv
更多内容:https://docs.docker.com/storage/volumes/和https://docs.docker.com/compose/#preserve-volume-data-when-containers-are-created
如果要使用Azure:https://github.com/Azure/azurefile-dockervolumedriver
和其他插件:https://docs.docker.com/engine/extend/legacy_plugins/
关于c# - 从Docker容器中的.NET Core App访问主机上的CSV文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62447815/