javydreamercsw
javydreamercsw

Reputation: 5089

Equal Dockerfiles but different base image

I'm barely new to Docker but have played around for a bit. I was able to make a Docker file that just has one line difference between the various host OS. Is there a way to avoid having multiple files like this with just the from line different?

For example:

  1. FROM ubuntu:16.04
  2. FROM centos:7.4.1708

Upvotes: 1

Views: 77

Answers (2)

mutableVoid
mutableVoid

Reputation: 1506

I think something like this is possible, but it seems to have its limitations.

For instance, say I want to build two images with the same "lower layers" for a cuda 11.4 and cuda 11.8 base image. Then I can use the following construct:

ARGS TARGET="cuda11.8"

# CUDA 11.4 Base (deprecated)
FROM nvidia/cuda:11.4.2-cudnn8-runtime-ubuntu20.04 as cuda11.4
# Custom instructions for this base:
RUN apt-get update && apt-get -y upgrade && apt-get -y install  python3.9

# CUDA 11.8 Base
FROM nvidia/cuda:11.4.2-cudnn8-runtime-ubuntu20.04 as cuda11.8
# Different custom instructions for the other base 
RUN apt-get update && apt-get -y upgrade && apt-get -y install  python3.10


FROM ${TARGET}
[everything shared for the different base image builds]

It is also possible to specify the name of the base image directly as ARG.

Build the image with docker build --build-arg 'TARGET=cuda11.4' for an image based on cuda11.4 and without an argument for the default base image.

Advantages:

  • no "duplicate code", because the shared steps are all listed underneath the last stage

Disadvantages:

  • The caller needs to keep track of all the names you give the base images and needs to issue a separate call for every image afaik.
  • The shared instructions have to appear in the layers below the "custom" instructions, e.g., if you want to install a different version of a package "later on" (at lower layers of the docker file), that is not directly possible afaik.

Edit In my research in trying to accomplish what you described in your question I just saw a blog post with more information that might be interesting.

Upvotes: 1

six8
six8

Reputation: 2990

Not with Dockerfiles themselves. You can create one Dockerfile as a template and use scripts to generate the various OS flavored Dockerfiles on-demand just before build.

For example, ElasticSearch Docker uses Jinja2 templates for Dockerfiles. They don't modify the FROM, but there's plenty of other templated usage that serves as example.

Upvotes: 1

Related Questions