Using Dockerfiles to Build and Run Locally

Learn about using sequential and multistage Dockerfiles and adding and configuring services in a Docker Compose file for local development.

Earlier in this chapter, we leveraged the Docker plugin for Visual Studio to generate Dockerfiles for each of the three services. As noted, the generated files contain several FROM directives, which allow Docker to use a specific image when building that layer. In some cases, Dockerfiles can be very simple—sequential lines installing or configuring aspects of the image for optimal use. But when does it make more sense to use a sequential file instead of one that has multiple build stages?

Sequential vs. multistage files

Chances are, if we have Docker experience, we’ve constructed a few Dockerfiles already. Starting off, we might have taken a base image and added a few programs to it, installed specific frameworks on it, or even configured more complex options for the image itself. A good rule to follow when writing a Dockerfile is to look at what needs to happen during the build process itself. For example, when building images that will ultimately run a compiled program, .NET or otherwise, we’ll see multistage files in most cases. The reason for that is simple—it allows us to separate the building of the application from the packaging and configuration required to run the application.

Take the command API, for example. The Dockerfile generated has four stages in it, where it leverages two distinct base images. The intent is to ensure an optimal runtime image is used as the base and that an optimal SDK image is used to build the service. This gives each relevant stage a way to be separated but combined at the end of the process. When building an image for running a specific workload, we can opt to use a sequentially-ordered Dockerfile because it might not need to keep things separated during the build phase. Take a moment and examine the three services’ Dockerfiles that were generated earlier.

Get hands-on with 1200+ tech skills courses.