Dockerfile FROM + ARG trick — parameterized dockerfile base image

Marcos Cano
1 min readOct 17, 2019

For long time I thought that it was impossible to parameterize FROM instruction in a Dockerfile.

FROM node:10-alpine

Let’s say you want to reuse your Dockerfile (DRY) for multiple applications but with different versions of node (this is just one of multiple examples):

  • APP_1: node:10-alpine
  • APP_2: node:12-alpine

You probably ended up creating 2 Dockerfiles with different FROM instructions but basically the same content.

Enter the trick

One can parameterize the FROM instruction using an ARG instruction above!

# MAGIC! if no arg provided default to "10-alpine"ARG node_version=10-alpine
FROM node:${node_version}
COPY package.json .
RUN npm install
# we can use ARG for other thingsARG app_id=1COPY packages/app_${app_id} .CMD ["node", "app.js"]

and you can use build-args to specify:

  • which version tag of node image you want to use
  • even specify which folders to copy
# build app_1app_id=1
docker build --build-arg "node_version=10-alpine" --build-arg "app_id=${app_id}" -t myapp:${app_id} .
# build app_2app_id=2
docker build --build-arg "node_version=12-alpine" --build-arg "app_id=${app_id}" -t myapp:${app_id} .

There you have it, hope you like it!

Q. What is the first instruction in a Dockerfile?
A. FROM not really

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Marcos Cano
Marcos Cano

Written by Marcos Cano

Devops evangelist and enthusiast, “dockerizing” everything, automate all the things! Currently Docker Guatemala community leader and mentor

No responses yet

Write a response