Start learning free

LESSON 152 OF 173 · BACKEND: SHIPPING IT

Start the App in C#

Practice

Your Dockerfile already builds an image with .NET, the shop's packages and the shop itself, compiled into /app/out. But an image only says what is inside it. It must also say how the app starts: EXPOSE notes the port the app listens on, and CMD is the command a container runs when it starts. dotnet followed by the path of a compiled .dll starts that app at once, with nothing to compile.

Write CMD as a JSON list: each word in double quotes, separated by commas, inside [ ]. Docker then starts the program directly, not through a shell, so the stop signal of docker stop reaches it. For another app, a small server on port 5000, it would look like this:

EXPOSE 5000
CMD ["dotnet", "server.dll"]

In the C# list, a quote inside a string is written \". A container has its own network: inside it, localhost is the container itself, so a server in a container must listen on every address. ASPNETCORE_HTTP_PORTS=8000, which your Dockerfile sets with ENV, does just that. To reach the shop from your computer, docker run -p publishes a port, your computer's port first, then the container's: -p 9000:5000 sends your computer's port 9000 to the container's port 5000.

When your code is done, the check prints:

$ docker build -t shop .
The image: the .NET 8.0 SDK, the packages and the shop, compiled into /app/out
EXPOSE 8000: the app listens on port 8000 in the container (a note for whoever runs the image, it opens nothing by itself)
CMD: when the container starts, it runs dotnet out/shop.dll
JSON list form: dotnet is the main process of the container, so the stop signal of docker stop reaches it
In the container: dotnet runs out/shop.dll from /app, and the shop listens on port 8000, its ASPNETCORE_HTTP_PORTS setting (set with ENV)
$ docker run -p 8000:8000 shop
-p 8000:8000: port 8000 of your computer goes to port 8000 of the container
http://localhost:8000/ -> port 8000 of the container -> dotnet -> out/shop.dll: the shop answers

Your task: add two lines to the list dockerfile: EXPOSE 8000, and a CMD that runs dotnet out/shop.dll as a JSON list. Then, below the list, store the command that starts a container from the image shop, publishing port 8000, in the string runCommand.


Assignment
Follow the Coding Tutorial to add the EXPOSE and CMD lines to the Dockerfile and write the docker run command.


Hint
The CMD line has double quotes inside, so write each of them as \" in the C# string. In -p, your computer's port comes first, then the container's. Until runCommand exists, the check can't compile: C# reports error CS0103.


STEP 1 OF 3
    Ctrl + Enter to check

    Ship Dockerfile Run in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free