How can I compile a single file (or several) for a simple csharp application using a docker file? My goal is to create a small csharp repl similar to the w3 schools one here. I've taken a look at this question but it does not suit my needs. I do not have a .csproj file, I am starting with a simple main.cs file like this:
using System;
using System.Collections.Generic;
using System.Linq;
class MainClass {
static void Main() {
Console.WriteLine("Hello World!");
}
}
I would like to know I can take the above code as a string and use a dockerfile to compile and run it to get the output. Specifically, what base image can I use and do I need to install any other packages before I can do this? The dockerfile below is taken from the other stack overflow question which seems reasonable but I don't want to compile an asp.net program.
FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /app
COPY <your app>.csproj .
RUN dotnet restore <your app>.csproj
COPY . .
RUN dotnet publish -c Release -o out
FROM microsoft/dotnet:2.2-aspnetcore-runtime AS runtime
WORKDIR /app
COPY --from=build /app/out ./
ENTRYPOINT ["dotnet", "<your app>.dll"]
You can use the command dotnet new console to create a basic console app project and then copy your file on top of the generated Program.cs file to replace it.
I've taken the liberty of replacing your .NET core 2.2 images with .NET 6.0 ones, as the 2.2 ones aren't supported anymore.
If you name your file with the code in it 'MyFile.cs' and use this Dockerfile, it should work
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /app
RUN dotnet new console
COPY MyFile.cs Program.cs
RUN dotnet publish -c Release -o out
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app/out .
ENTRYPOINT ["dotnet", "app.dll"]
Build and run with
docker build -t testimage .
docker run --rm testimage
With the changes made to .NET 6 you no longer need a lot of the boilerplate C# code, so you can also reduce your program file to a single line
Console.WriteLine("Hello World!");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With