Mounting Volumes in Docker with Visual Studio
This technique is ideal for local development within Visual Studio. You can easily mount local files into a docker container by modifying the MSBuild commands of the project.
Project File’s MSBuild Commands
This code came from a .NET Core 3.1 project.
1 2 3 4 5 |
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <DockerfileRunArguments>-v "C:\data:/data"</DockerfileRunArguments> </PropertyGroup> </Project> |
Using MSBuild Variables
Another way to do this is to use the MSBuild Variable $(MSBuildStartupDirectory). Since the Dockerfile Context is in the root of the solution we will use the MSBuild variable to map to the root.
1 2 3 4 5 6 7 8 9 10 |
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>net8.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <DockerfileContext>..\..</DockerfileContext> <DockerfilebuildArguments>--build-arg NUGET_USER=$(NUGET_USER) --build-arg NUGET_PAT=$(NUGET_PAT)</DockerfilebuildArguments> <DockerfileRunArguments><strong>-v $(MSBuildStartupDirectory)\certs\:/certs/</strong></DockerfileRunArguments> <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS> </PropertyGroup> |
Docker Volume Mounting
The docker -v or –volume flag is used to designate a volume mount in a Docker command. There’s another way to mount volumes using the “–mount” flag. This originally was only for Docker swarm environments but since the release of Docker 17.06, this can be used in standalone containers. The “–mount” command is specifically used with mounting services.
# mounting an existing container
docker run -v C:\data:/data
Read Only Access
If you want to restrict access to read-only… modify the flag to look like this “-v C:\data:/data:ro“
You can read more about Docker volume mounting here.