Docker on Windows
上QQ阅读APP看书,第一时间看更新

Understanding the Dockerfile

The Dockerfile is the source code for an image. The complete code for the PowerShell image is just three lines:

FROM microsoft/nanoserver
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 that's not mandatory. Also by convention, you save the text in a file called Dockerfile, but that's 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 that Dockerfile line by line:

  • FROM microsoft/nanoserver uses the image called microsoft/nanoserver as the starting point for this image
  • COPY scripts/print-env-details.ps1 c:\\print-env.ps1 copy the PowerShell script from the local computer into a specific location on the image
  • CMD ["powershell.exe", "c:\\print-env.ps1"] specifies the startup command when a container runs, in this case 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 has made the Nano Server image available on Docker Hub, and that image is called microsoft/nanoserver. The first time you use the image, Docker will download it 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.

Dockerfiles use the backslash as an escape character in order to continue instructions onto a new line. This clashes with Windows file paths, so you have to write c:\print.ps1 as c:\\print.ps1 or c:/print.ps1. There is a nice way to get around this, using a processor directive at the start of the Dockerfile, which I'll demonstrate later in the chapter.

How do you know PowerShell is available for use? It's part of the Nano Server 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, copy or download files into the image, extract ZIP files 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 wanted to build an exact clone of Microsoft's Nano Server image, you could do that with just a FROM statement in your Dockerfile.