user137
user137

Reputation: 759

Pass args to the Dockerfile from docker-compose

I have the next configuration of my prod env:

docker-compose-prod.yml

version: '3.3'
services:
  nginx:
    build:
      context: nginx
      dockerfile: Dockerfile
      args:
        LANDING_PAGE_DOMAIN: ${LANDING_PAGE_DOMAIN}
    container_name: nginx   
    networks:
      - app-network

Dockerfile

FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY production/* /etc/nginx/conf.d/

ARG LANDING_PAGE_DOMAIN
RUN sed -i s/{LANDING_PAGE_DOMAIN}/${LANDING_PAGE_DOMAIN}/g /etc/nginx/conf.d/landing.conf

EXPOSE 80 443

So when I try do build it I got next warning:

docker-compose -f docker-compose.production.yml build --build-arg LANDING_PAGE_DOMAIN="test.com" nginx

WARNING: The LANDING_PAGE_DOMAIN variable is not set. Defaulting to a blank string.

Where I made a mistake?

Upvotes: 40

Views: 37258

Answers (3)

esboych
esboych

Reputation: 1075

There are 2 options how to make it work:

  1. Use existing code in docker-compose-prod.yml and set environment variable LANDING_PAGE_DOMAIN:

    export LANDING_PAGE_DOMAIN=test.com

    then run build step w/o passing the build args:

    docker-compose -f docker-compose.production.yml build nginx

  2. Comment / delete 2 lines from docker-compose-prod.yml file:

        args:
          LANDING_PAGE_DOMAIN: ${LANDING_PAGE_DOMAIN}

Then you'll be able to build it with passing arguments at build time:

docker-compose -f docker-compose-prod.yml build --build-arg
LANDING_PAGE_DOMAIN="test.com" nginx

The reason why it currently doesn't work is because those 2 lines in docker-compose-prod.yml file explicitly sets the LANDING_PAGE_DOMAIN argument to be populated by ${LANDING_PAGE_DOMAIN} environment variable.

And when you run docker-compose build with --build-arg option it doesn't set any env vars but literally passes arguments for build step.

Upvotes: 8

Nathanael
Nathanael

Reputation: 982

the key word ARG has a different scope before and after the FROM instruction

Try using ARG twice in your Dockerfile, and/or you can try the ENV variables

ARG LANDING_PAGE_DOMAIN
FROM nginx:alpine

COPY nginx.conf /etc/nginx/nginx.conf
COPY production/* /etc/nginx/conf.d/

ARG LANDING_PAGE_DOMAIN
ENV LANDING_PAGE_DOMAIN=${LANDING_PAGE_DOMAIN}

RUN sed -i s/{LANDING_PAGE_DOMAIN}/${LANDING_PAGE_DOMAIN}/g /etc/nginx/conf.d/landing.conf

EXPOSE 80 443

Upvotes: 20

rokpoto.com
rokpoto.com

Reputation: 10736

You need to add ARG LANDING_PAGE_DOMAIN=value to your Dockerfile:

From the docs

The ARG instruction lets Dockerfile authors define values that users can set at build-time using the --build-arg flag

Upvotes: 0

Related Questions