docker-compose build args not passing to Dockerfile

The defined arguments on the compose file are available on the Dockerfile but only before and on the FROM. After the FROM the arguments are not available:

An ARG declared before a FROM is outside of a build stage, so it can’t be used in any instruction after a FROM. – from docker docs

Why is the argument NODE_VERSION working?
The argument NODE_VERSION isn’t working after the FROM. The argument is only used on the FROM (FROM node:8). After FROM there is a environment variable of the image with the same name. So you echo the environment variable of the image instead of the argument of your compose file.

But you can use the default value of the argument after FROM:

To use the default value of an ARG declared before the first FROM use an ARG instruction without a value inside of a build stage. – from docker docs

ARG NODE_VERSION

FROM node:$NODE_VERSION

ARG HELLO

RUN echo "-> $HELLO"
RUN echo "-> $NODE_VERSION"

To use and show the node version defined in the arguments you need to rename this argument. So you can use the following to show all your arguments and the environment variable of the image:

Dockerfile:

ARG CUSTOM_NODE_VERSION

FROM node:$CUSTOM_NODE_VERSION

ARG CUSTOM_NODE_VERSION
ARG HELLO

RUN echo "-> $HELLO"               #output: 5
RUN echo "-> $NODE_VERSION"        #output: 8.9.4
RUN echo "-> $CUSTOM_NODE_VERSION" #output: 8

docker-compose.yml:

version: "3"

services:
  ei:
    build:
      context: .
      dockerfile: Dockerfile
      args:
        CUSTOM_NODE_VERSION: 8
        HELLO: 5

Leave a Comment