skip to Main Content

My directory structure looks like this.

|
|
— Dockerfile
| — .env

Content of .env file looks like this.

VERSION=1.2.0
DATE=2022-05-10

I want to access VERSION and DATE as environment variable both during build time and run time. So ENV is the one I should use. I know that.
How exactly can I do that ?

I tried using RUN command in Dockerfile like

RUN export $(cat .env)

But, it can only be accessed during runtime and not build time.
So, how can this be achieved with ENV ?

I can do it manually like

ENV VERSION 1.2.0
ENV DATE 2022-05-10

But, it is inefficient when I have many environment variables.

P.S. I cannot use docker-compose because the image is going to be used by kubernetes pods, so.

3

Answers


  1. You could firstly export these variables as environmetal variables to your bash

    source .env
    

    Then use --build-arg flag to pass them to your docker build

    docker image build --build-arg VERSION=$VERSION --build-arg DATE=$DATE .
    

    Next in your dockerfile

    ARG VERSION
    ARG DATE
    ENV version=$VERSION
    ENV date=$DATE
    

    As a result, for example you can access the variables in your build phase as VERSION and in your container as version

    Login or Signup to reply.
  2. You can specify the env_file in the docker-compose.dev.yml file as follows:

    
    # docker-compose.dev.yml
    
    services:
      app:
        ...
        env_file:
            - .env.development
    
    

    and you have to have a .env.development file containing all the environment variables you need to pass to the docker image.

    e.g.:

    # .env.development
    
    REACT_APP_API_URL="https://some-api-url.com/api/graphql"
    
    
    Login or Signup to reply.
  3. What I’ve read from others says that there is no "docker build –env-file…." option/apparatus. As such, this situation makes a good argument for shifting more of the content of the dockerfile to a shell script that the dockerfile simply copies and runs, as you can source the .env file that way.

    greetings.sh

    #!/bin/sh
    
    source variables.env
    echo Foo $copyFileTest
    

    variables.env

    export copyFileTest="Bar"
    

    dockerfile

    FROM alpine:latest
    
    COPY variables.env .
    RUN source variables.env && echo Foo $copyFileTest  #outputs: Foo Bar
    COPY greetings.sh .
    RUN chmod +x /greetings.sh
    RUN /greetings.sh               #outputs: Foo Bar
    
    RUN echo $copyFileTest          #does not work, outputs nothing
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search