Containerizing a Legacy .NET Service: What Breaks When the Server Becomes a Container

Putting an application into a container looks like packaging. Write a Dockerfile, copy the build output, start it. For a service that has lived on one server for years, the Dockerfile is the smallest part. The service has grown assumptions about that server, and a container breaks most of them: it is replaced without notice, runs in several copies, has a file system it may not write to, and is told to stop instead of being switched off.

This case takes such a service, measures what happens when it is put into an image unchanged, and then makes it fit. The code is on GitHub: chudovo/application-modernization, case 09.

At a glance

BeforeAfter
Runs asa process on one Windows servera Linux container, non-root, read-only file system
Configurationa file next to the binaries, API key includedenvironment variables, no default for the secret
Logsfiles in a folder under the applicationJSON lines on standard output
Documents and their listlocal folder, list in memorya mounted volume, nothing in memory
Time zone and culturewhatever Windows providesnamed explicitly, data in the image
Stoppingthe process is killedSIGTERM, requests in flight finish
Tests passing10 of 10 scenarios10 of 10 scenarios, 9 of 9 container tests

The service

It is a document inbox. Clients upload documents into mailboxes, list and download them, and fetch a daily report. It is German: sizes are shown as 1,5 KB, and the day of the report is the German calendar day, so an upload at 22:30 UTC on 1 July belongs to 2 July. The code is honest about what it relies on:

// Assumption: the application may write into its own folder.
var logFolder = Path.Combine(AppContext.BaseDirectory, "logs");
Directory.CreateDirectory(logFolder);

// Assumption: there is one process and it never restarts, so the list of documents can live in memory.
var index = new ConcurrentDictionary<string, List<Document>>();

// Assumption: the server knows the German culture and the Windows name of the German time zone.
var german = CultureInfo.GetCultureInfo("de-DE");
var berlin = TimeZoneInfo.FindSystemTimeZoneById("W. Europe Standard Time");

// Assumption: file names are not case-sensitive and the backslash separates folders.
var template = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, @"templates\dailyreport.txt"));

Every one of these is true on the server it was written for. None of them is a bug there.

Two kinds of tests

Ten scenarios describe what clients see over HTTP. They run against the old service as a plain process on Windows and against the container, so they prove that nothing changed for clients.

Nine container tests describe what a platform expects of a service beyond answering requests. They drive Docker themselves: start the image under the restrictions a careful platform applies, stop it, replace it, run two copies. One of them:

[Fact]
public async Task An_upload_in_progress_is_finished_when_the_container_is_told_to_stop()
{
    var service = await StartAsync(extra: "-e Processing__DelayMs=4000");

    var upload = InboxClient.UploadAsync(service.Http, "box", "unterwegs.txt", new byte[500]);
    await Task.Delay(1000);
    Docker($"stop -t 20 {service.Name}");   // SIGTERM, then 20 seconds of patience, as a platform does

    Assert.Equal(HttpStatusCode.Created, (await upload).StatusCode);

    var next = await StartAsync();           // a new container on the same volume
    Assert.Equal(1, (await Json(await next.Http.GetAsync("/api/mailboxes/box/documents"))).GetArrayLength());
}

The first attempt

The usual first step is a Dockerfile around the application as it is, on the smallest base image:

# The first attempt: the application exactly as it is, in the smallest official image.
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY before/src/Inbox/ .
RUN dotnet publish -c Release -o /app

FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT dotnet Inbox.dll

It builds without a warning. Against the tests:

ImageResult
Old service on the alpine imagedoes not start: only the invariant culture is supported in globalization-invariant mode
Old service on the default image8 of 10 scenarios pass, all 9 container tests fail

The alpine image contains no culture data and no time zone database. The service asks for the German culture when it starts and stops right there. On the default image it starts, and the two report scenarios fail: the template is addressed as templates\dailyreport.txt, the file on disk is Templates/DailyReport.txt, and on Linux a backslash is an ordinary character in a file name.

The nine container tests all fail, each for a reason of its own. Under the restrictions the service does not start at all, because it cannot create its log folder on a read-only file system. With the restrictions removed, to see how far it gets:

A platform expectsThe old service in a container
Starts read-only, without privilegeswrites its logs into its own folder
Does not run as rootthe image has no user set
Says whether it is alive and readyhas no health endpoints
Documents survive a replaced containerthe list of documents is in memory
Two copies serve the same documentseach copy has its own list and its own numbering
An upload in progress finishes on stopdocker stop waits the full 20 seconds, then kills it; the upload is lost
Logs on standard outputits own log goes to a file inside the container
Does not start without its secretstarts with the key from the settings file

The stop test deserves a sentence. The Dockerfile ends with ENTRYPOINT dotnet Inbox.dll. In that form Docker starts a shell, the shell starts the application, and the shell does not pass the stop signal on. The application never learns that it should stop. It is one of the most common lines in Dockerfiles.

The image

FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
WORKDIR /src
COPY after/src/Inbox/ .
RUN dotnet publish -c Release -o /app
# The final image has no shell, so the data folder is prepared here and copied with its owner.
RUN mkdir /data

# "chiseled": no shell, no package manager, a non-root user.
# "extra": includes the culture data and the time zone database that alpine leaves out.
FROM mcr.microsoft.com/dotnet/aspnet:10.0-noble-chiseled-extra
WORKDIR /app
COPY --from=build /app .
COPY --from=build --chown=$APP_UID:$APP_UID /data /data
VOLUME /data
USER $APP_UID
EXPOSE 8080
# Exec form: the application is process 1 and receives SIGTERM itself.
ENTRYPOINT ["dotnet", "Inbox.dll"]

Three decisions are in it. The base image is a chiseled one: no shell, no package manager, a non-root user by default. It is the variant with culture and time zone data, because this application needs both. And the entry point is in exec form, so the application receives the stop signal itself.

State leaves the container

Documents and their descriptions are files in a mounted volume, and nothing is kept in memory. A new container continues where the old one stopped, and two copies see the same documents. The interesting part is the numbering. With two copies there is no shared counter, so a number is claimed by creating a file:

// A document number is claimed by creating its description file. CreateNew fails if another copy of the
// service took this number a moment ago. Then try the next one.
FileStream claim;
try
{
    claim = new FileStream(Path.Combine(Folder(box), $"{id}.json"), FileMode.CreateNew);
}
catch (IOException) when (File.Exists(Path.Combine(Folder(box), $"{id}.json")))
{
    continue;
}

The test sends twenty uploads to two copies at once and requires twenty different numbers. The first version of this code failed that test: it only retried when the other copy had not written its content yet, and the other copy was sometimes faster.

Configuration, logs and health

// A secret has no default: without it the service does not start.
if (string.IsNullOrEmpty(apiKey))
{
    log.LogCritical("ApiKey is not configured. Set the ApiKey environment variable.");
    await app.DisposeAsync();   // flushes the log before the process ends
    return 1;
}

// Liveness: the process answers. Readiness: it can do its job, which here means the volume is writable.
app.MapGet("/healthz/live", () => Results.Ok(new { status = "live" }));
app.MapGet("/healthz/ready", () => store.IsWritable()
    ? Results.Ok(new { status = "ready" })
    : Results.Json(new { status = "storage is not writable" }, statusCode: 503));

The old settings file contained the API key. In an image that means every copy of the image carries the secret, and a container without configuration runs with a key everyone knows. Now the service refuses to start without it. Logs are JSON lines on standard output, and since the application writes no files of its own, the file system can be read-only. Readiness is separate from liveness: with the volume mounted read-only, the service is alive and not ready, and a platform would send it no requests.

What is verified, and what is not

CheckResult
10 scenarios against the old service as a process, Windows10 / 10
10 scenarios against the container, Linux10 / 10
9 container tests against the image9 / 9
Stop with an upload in progressnew image: stopped after 3.1 s, upload completed; first attempt: killed after 20.2 s, upload lost
  • Not a real platform. The tests drive Docker on one machine. Kubernetes or a cloud container service, with their probes, rolling updates and autoscaling, are not involved. The restrictions and signals are the ones those platforms use.
  • Not a real shared store. Two copies share a Docker volume on one host. In a cloud the equivalent is a network file share or, better, object storage and a database. The file-based store shows the principle, not a design for scale.
  • Not a load test. Twenty parallel uploads check correctness, not throughput.
  • Not Windows containers. Applications that cannot leave Windows have a different path.

One number does not flatter the result. The final image is bigger than the first attempt: 239 MB against 179 MB on alpine, as Docker reports them. The culture and time zone data are the difference. A small image that cannot format a date is not a saving.

Run it yourself

You need the .NET 10 SDK and Docker:

docker build -f after/Dockerfile -t inbox:after .
docker run -d --read-only --tmpfs /tmp --cap-drop ALL -e ApiKey=demo-key -e Clock__FixedUtc=2026-07-01T22:30:00Z -p 127.0.0.1:5090:8080 inbox:after
dotnet test tests/Inbox.Tests

When this path fits

Containerizing is the right first step into the cloud for a service that works and has to keep working: the code changes are small and each has a test. It is not a rehost. What the first attempt showed is that an image which builds and answers requests proves nothing; the problems appear when the container is restricted, stopped, replaced or doubled, which is to say in production. Where containerization sits among the other ways of moving a system is covered in the guide to cloud migration for legacy systems.

If you need a team for a move like this, see our comparison of modernization vendors.

Eugene started his career at Chudovo in 2015. The expert is responsible for advisory services that include but are not limited to close communication with the clients, analyzing their needs, designing tailored software strategies, etc. Throughout the practice at Chudovo, an IT consultant took part in over 17 projects, covering a wide range of client services and solving customer pains from the business perspective. With Eugene’s involvement, the customers were able to build an efficient strategy for business growth as well as to set up a long-term technology roadmap. Eugene takes an active part in software development projects in the role of IT consultant and composes proposals for the customers.