Blankman
Blankman

Reputation: 267270

How to pass ENV arguments in my Dockerfile when using docker-compose

I have a docker-compose.yml that has a section:

myservice:
  env_file:
    - myvars.env

My env variable file has:

myvars.env:
SOME_VAL=123

And then in my Dockerfile I have this:

..
RUN echo "some_val ${SOME_VAL}"
ENTRYPOINT bash ${APP_BASE}/run.sh SOME_VAL=${SOME_VAL}

When I run docker-compose up, the value of some_val is empty.

  1. Why is SOME_VAL not accessible in my dockerfile?
  2. How do I pass the env variable SOME_VAL to my run.sh script?

Upvotes: 1

Views: 3421

Answers (2)

David Maze
David Maze

Reputation: 159761

When you docker-compose build an image, it only considers the build: sections of the docker-compose.yml file. Nothing else from any other part of the file is considered. environment: and env_file: settings aren't available, nor are volumes: nor networks:. The only way to pass settings in is through the Dockerfile ARG and the corresponding Compose args: settings, and even then, you only want to use this for things you'd "compile in" to the image.

Conveniently, shell scripts can directly access environment variables already, so you don't need to do anything at all; just use the variable.

#!/bin/sh
# run.sh

echo "SOME_VAL is $SOME_VAL"
# Dockerfile
FROM busybox
WORKDIR /app
COPY run.sh .
# RUN chmod +x run.sh
CMD ["./run.sh"]
# docker-compose.yml
version: '3.8'
services:
  echoer:
    build: .
    env_file:
      - my_vars.env
    # environment:
    #   SOME_VAL: foo

Upvotes: 0

emi
emi

Reputation: 3078

You need to declare the variable with ENV in the Dockerfile before using it:

ENV variables are also available during the build, as soon as you introduce them with an ENV instruction.

Dockerfile
ENV SOME_VAL
RUN echo "some_val ${SOME_VAL}"
ENTRYPOINT bash ${APP_BASE}/run.sh SOME_VAL=${SOME_VAL}

Upvotes: 1

Related Questions