Goal: To run a .NET api in a docker container, and use docker compose to make it easier.
-
Chocolatey -
choco install dotnetcore-sdk
Run the API
dotnet run --project MicroserviceWorkshop
The API should start and show you the uris to access it from. Verify the API is running by navigating there in your browser.
To build a docker container to host our app we must create a Dockerfile.
We are going to create a Dockerfile that builds and publishes the artifacts of our app from the dotnet sdk container. We will then use those artifacts in our dotnet core runtime container as our entrypoint.
- Create a file named
Dockerfile
in the root of the project. Add the following line to load the dotnet sdk container.
FROM microsoft/dotnet:2.1-sdk AS build-env
- Copy the source code from our project to the container.
COPY ./MicroserviceWorkshop /app/src/
If you build and run the container now, you can see our source files in the /app/src/
directory.
docker build .
docker run -p 5000:80 -it --name=microservice-workshop <container-id>
cd /app/src
ls
exit
docker rm microservice-workshop
- Build and publish the artefacts.
WORKDIR /app/src
RUN dotnet publish -c Release -o ../out
- In the same Dockerfile, load the dotnet runtime container.
FROM microsoft/dotnet:2.1-aspnetcore-runtime
- Copy the artefacts from the dotnet sdk container into the
app
directory of the dotnet runtime container.
WORKDIR /app
EXPOSE 80
COPY --from=build-env /app/out .
- Run
ENTRYPOINT ["dotnet", "MicroserviceWorkshop.dll"]
Now that we have a Dockerfile we can build and run it.
docker build .
docker run -p 5000:80 --name=microservice-workshop <container-id>
Test it by navigating to [http://localhost:5000]
Stop the running container
docker stop microservice-workshop
Remove the container
docker rm microservice-workshop
Docker commands can quickly become unweildy and very often we want to launch a bunch of containers that interact with each other together. This is where the docker-compose
command comes in.
Notice the docker-compose.yml
file; this file is picked up by the docker-compose
command. The file contains information about the port number mappings in this case but there are lots more things you can do with it. As ours is a simple case, this is all we need.
Run docker-compose up
to launch the container.