abelcastro.dev

Using variables in the Dockerfile FROM statement

2021-06-01

Docker

This demonstrates how to use a variable as image for the Dockerfile FROM statement.

Given this docker-compose.yml / Dockerfile setup:

docker-compose.yml

version: '3'
services:
	postgres:
	    build:
	      context: .
	      dockerfile: ./compose/postgres/Dockerfile
	    volumes:
				- postgres_data:/var/lib/postgresql/data
	    env_file:
	      - .env
volumes:
    postgres_data:

Dockerfile

FROM postgres:12.3

The Postgres service will always use the same FROM image defined in the Dockerfile. If we want instead to set the FROM image using a variable, we can do the following:

Docker-compose.yml

  • pass a build_image arg with a default value
version: '3'
services:
	postgres:
	    build:
	      context: .
	      dockerfile: ./compose/postgres/Dockerfile
	      args:
	       build_image: "${BUILD_IMAGE:-postgres:12.3}" 
	    volumes:
				- postgres_data:/var/lib/postgresql/data
	    env_file:
	      - .env
volumes:
    postgres_data:

Dockerfile

  • use the passed build_image arg in the FROM statement
# this will be the default image
ARG build_image="postgres:12.3"

# The default image will be overriden if other build image is passed as ARG
ARG build_image=$build_image
FROM $build_image

.env

  • Pass the desired value in .env
BUILD_IMAGE=postgis:9.6