Setup aspnet core app with vagrant and docker

Create dotnet application. For example, a webapi

The webapi will be named Bustroker.Notes.WebApi.

dotnet new webapi -n Bustroker.Notes.WebApi

Create linux VM with Vagrant

I rather a linux vm to work with docker. Check the post Vagrant VM provision & vagrant commands cheathsheet for Vagrantfile and provision script. From there select the tools required in the VM. In the example port 8080 of VM is mapped to port 8080 in host. If another is required, it needs to be set.

Setup docker

Dockerfile content

FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o publish

# Build runtime image
FROM mcr.microsoft.com/dotnet/sdk:5.0
WORKDIR /app
COPY --from=build-env /app/publish .
ENTRYPOINT ["dotnet", "Bustroker.Notes.WebApi.dll"]

I also like to have docker compose, so I don’t have to run large docker run ... command with ports and blah blah. Easier to just docker-compose up So, docker-compose.yml file content

services:
  webui:
    environment:
      - ASPNETCORE_ENVIRONMENT=docker-compose
    build: .
    ports:
      - "8080:80"

Here the app is listening in port 8080 of the VM. Also, the VM 8080 port is mapped to the host’s 8080 (configured in Vagrant VM step before). So the 8080 port of Vagrant VM is accessible from host’s localhost:8080.

Run it

Inside Vagrant VM, cd into app folder and go

docker-compose up

In the host machine, open browser to localhost:8080. To clarify on the ports, the docker-compose es exposing app’s port (80) in VM 8080 port, which is mapped to host’s 8080 through Vagrant config.