A couple of years ago I had to learn how to make ODATA API’s to allow access to some of our applications at work. I was amazed at how easy Microsoft makes this process for you in Visual Studio, there’s so much scaffolding that doesn’t really change between projects and they just… do it all for you automatically? How nice!
If you’ve read my past few blog entries you’ll know I’m a big fan of self-hosting and Docker containers, and now that Microsoft’s newest versions of DotNet can run on Linux this got me thinking… how hard would it be to make an ODATA API project into a Docker container? As it turns out, very easy!
I took an old joke script I’d made and turned it into an ODATA Web API to help me learn the ropes. It’s basically a mad-lib generator that spits out random bits of text you can configure. Very dumb, but a perfect candidate to test containerizing.
Let’s take a look at the Dockerfile I made for containerizing that project:
As you can see there’s almost nothing to it. It’s way less complicated than my last Dockerfile example. Let’s go over each part:
FROM mcr.microsoft.com/dotnet/aspnet:6.0
Microsoft provides their own base images that have the ASP.Net for Linux runtime installed and ready to go, so we just have to specify one of those images to build off of (when I made this, asp.net 6.0 was the latest version available, just make sure you match the version your project is using)
WORKDIR /app
COPY . /app
First you have to compile the application in Visual Studio, but assuming you’ve got it in the same directory as this Dockerfile, you simply need to run this copy all command to pull the whole project into the image.
ENV ASPNETCORE_URLS http://*:80
The ENV command lets you set environment variables and we’re setting the ASPNETCORE_URLS to “http//:*:80”, which tells the DotNet runtime to listen on port 80 for any IP address it has
EXPOSE 80
This exposes port 80 externally so the container can use that port.
ENTRYPOINT ["dotnet", "TitleGeneratorAPI.dll"]
This line says when the container runs to call the compiled program (TitleGeneratorAPI.dll) in DotNet.
The ENTRYPOINT command is similar to CMD which we used last time, but allows you to pass in additional arguments (which we aren’t doing here, but you know, let’s mix it up a little).
And that’s really it. Build the image, spin up a container, and you’re good to go!
if you really want to, you can grab the compiled container for this example project from it’s DockerHub repo and see it in action.