Can't access env variables in RUN script.sh Dockerfile

I have this Dockerfile:

FROM php:5.6-apache
WORKDIR /var/www/html/

# ENV VARIABLES
ENV INI_FOLDER /usr/local/etc/php
ENV WWW_FOLDER /var/www

# ADD THE ENV CONFIGURATOR AND SET PERMISSIONS
ADD env.sh $WWW_FOLDER/
RUN chmod +x $WWW_FOLDER/env.sh

RUN /var/www/env.sh

The problems is that in env.sh I don’t have access to the variables set on the docker-compose (app.env, mysql.env). Is there any workaround to fix this?

docker-compose

version: '2.0'

services:
  app:
    env_file:
      - app/mysql.env
      - app/app.env
    volumes:
      - C:\Users\svirl\Documents\workspace\docker\my-app:/var/www/html/:rw
    build: app

Given this simple Dockerfile

FROM ubuntu

ENV FOO=bar

RUN echo $FOO

When i do a docker build ., then I got access to the environment.

Sending build context to Docker daemon 2.048 kB
Step 1 : FROM ubuntu
 ---> f49eec89601e
Step 2 : ENV FOO bar
 ---> Running in 516798aab23b
 ---> c706bdcdef80
Removing intermediate container 516798aab23b
Step 3 : RUN echo $FOO
 ---> Running in 539aaf884ccc
bar
 ---> 32708d862fc4
Removing intermediate container 539aaf884ccc
Successfully built 32708d862fc4

The idea is that the variable is from .mysql file in docker-compose, and I need it in env.sh … and there is empty.

the RUN steps are used to build the image. The docker-compose uses later that immutable image. So it’s just normal that the env in docker-compose has no effect to the immutable image.

If you want to react based on environment you can override your CMD. There you have full access to env also added later in compose.

2 Likes

So your recommendation is to use CMD [’/path/to/my/script.sh’] to override the default CMD and there I can use the ENV vars. Correct? If yes, Thank you.

yes. you could override CMD and/or ENTRYPOINT.

I did not fully understand the difference between those 2, the ENTRYPOINT is executed at each container start and the CMD?

just use CMD for now.