In the first 2 parts we learned how to use docker and run our console application in it. In this post we will run a web application that exposes an API over http.
If you are following along you will need the following:
- .NET SDK — https://dotnet.microsoft.com/en-us/download
- Visual Studio Code — https://code.visualstudio.com/
- Docker — https://www.docker.com
We will use the dotnet cli for this using the webapi project template. The project will be created inside the folder weather-api.
dotnet new webapi --no-https -o weather-api
This will create a sample application with a single http api, /weatherforecast.
Now, on to the docker file.
Navigate inside the weather-api folder and create a Dockerfile. Just like we did in the previous post. This time our base image will be aspnet runtime image. You can find it here : https://hub.docker.com/_/microsoft-dotnet-aspnet
Here is how the Dockerfile looks like.
In the COPY command the “.” indicates that it should be copied to the current working directory which we have set it as /container-app in the second line.
If you want know the basics of Dockerfile, take a look at the Part-2 of this series. The official documentation can be found here: https://docs.docker.com/engine/reference/builder/
We can now publish our application to folder called app and then build our docker image. Remember, docker image is the definition of what going to be in the container.
Here’s the command to publish it to an output folder called app.
dotnet publish -c release -o ./app
If you are following along, now is the time to build our docker image.
docker build -t dotnet-docker/weather-app:latest .
Now we will use this image to run it in a container.
docker run -it --rm dotnet-docker/weather-app:latest
Just like in out previous post, lets run our app in the container.
Great. It starts running and is listening on port 80. But hey, we can’t reach containers port from our machine. Our computer running the container is called the docker host.
Two things need to happen:
- The container must publish its port to be used from docker host.
- A mapping of docker host’s port to the container’s published port.
This is how we can do it with just one flag, -p. We run the container this way:
docker run -p 56565:80 -it --rm dotnet-docker/weather-app:latest
Run the app
Now, if we navigate to http://localhost:56565/weatherforecast , you will successfully receive a response from your api.
In this post we ran a http api from the container. We learned how to map ports from the container to the docker host. In the next one we will work on our Docker file to make it build our application and then copy and run our application too.
Until next time. Cheers.