Understanding Dockerfiles
A Dockerfile is just a deployment script which packages software into a Docker image. The complete code for the PowerShell image is just three lines:
FROM mcr.microsoft.com/windows/servercore:ltsc2019
COPY scripts/print-env-details.ps1 C:\\print-env.ps1
CMD ["powershell.exe", "C:\\print-env.ps1"]
It's pretty easy to guess what's happening even if you've never seen a Dockerfile before. By convention the instructions (FROM, COPY, and CMD) are uppercase and the arguments are lowercase, but this is not mandatory. Also by convention, you save the text in a file called Dockerfile, but this is not mandatory either (a file with no extension looks odd in Windows, but remember that Docker's heritage is in Linux).
Let's take a look at the instructions in the Dockerfile line by line:
- FROM mcr.microsoft.com/windows/servercore:ltsc2019 uses an image called windows/servercore as the starting point for this image, specifying the ltsc2019 version of the image and the registry where it is hosted.
- COPY scripts/print-env-details.ps1 C:\\print-env.ps1 copies the PowerShell script from the local computer to a specific location in the image.
- CMD ["powershell.exe", "C:\\print-env.ps1"] specifies the startup command when a container runs, which in this case is running the PowerShell script.
There are a few obvious questions here. Where does the base image come from? Built into Docker is the concept of an image registry, which is a store for container images. The default registry is a free public service called Docker Hub. Microsoft publishes some images on Docker Hub, but Windows base images are hosted on the Microsoft Container Registry (MCR).
The 2019 release of the Windows Server Core image is called windows/servercore:ltsc2019. The first time you use the image, Docker will download it from MCR to your local machine and then cache it for further use.
Where does the PowerShell script get copied from? When you build an image, the directory containing the Dockerfile is used as the context for the build. When you build an image from this Dockerfile, Docker will expect to find a folder called scripts in the context directory, containing a file called print-env-details.ps1. If it doesn't find that file, the build will fail.
How do you know PowerShell is available for use? It's part of the Windows Server Core base image, so you can rely on it being there. You can install any software that isn't in the base image with additional Dockerfile instructions. You can add Windows features, set registry values, copy or download files into the image, extract ZIP files, deploy MSIs and do whatever else you need.
This is a very simple Dockerfile, but even so two of the instructions are optional. Only the FROM instruction is mandatory, so if you want to build an exact clone of Microsoft's Windows Server Core image, you can do so with just a FROM statement in your Dockerfile, and call the cloned image anything you like.