Friday, February 4, 2022

[SOLVED] Avoid duplicate Dockerfile

Issue

I'm working on a .NET Core application that is shipped via Docker. My development environment is a Windows machine using Linux containers. The production environment is a Raspberry Pi.

Since the architectures between development and production differ (x64 vs. ARM), I have two different Dockerfile that only differ in exactly one line (the base image):

  • Development on x64: FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim AS base
  • Production on ARM: FROM mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim-arm32v7 AS base

Is it possible to avoid the two different files? If yes, how can I do so? Is it possible to have something like an if or can I reference another file (e. g. Dockerfile.common)?


Solution

For simple string substitutions like this you can use a Dockerfile ARG. If you're using this to set a FROM base image, it needs to be specified before any FROM lines. (For other uses it needs to be specified after the FROM line in each image stage that needs it.)

ARG BASE_IMAGE=mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim
FROM ${BASE_IMAGE} AS base

If you're building on ARM then you need to supply a docker build --build-arg option

docker build \
  --build-arg BASE_IMAGE=mcr.microsoft.com/dotnet/core/aspnet:3.1-buster-slim-arm32v7 \
  .

Docker doesn't have any conditionals or file inclusion capabilities beyond this.



Answered By - David Maze
Answer Checked By - Candace Johnson (WPSolving Volunteer)