3

I need to pass the environment variable in my Dockerfile like below. May i know the efficient way to do this. I tried using build args

docker build --build-arg myIP=123 --rm -t react_2811_1154 .

but it didnt work.

Here is my Dockerfile

ARG myIP

FROM node:11

ENV myIP1 $myIP


ENV REACT_APP_MOCK_API_URL=http://${myIP1}:8080/API
ENV REACT_APP_MOCK_API_URL_AUTH=http://${myIP1}:8080/API/AUTH
ENV REACT_APP_MOCK_API_URL_PRESENTATION=http://${myIP1}:8080/API/PRESENTATION

# set working directory
RUN mkdir /usr/src/app/
WORKDIR /usr/src/app/

COPY . /usr/src/app/.

RUN npm install 

#RUN npm start
CMD ["npm", "start" ]

So when i run my docker container i believe i dont want to send any environment variable to it.

Please advise.

Ranjith
  • 157
  • 1
  • 13
  • I don't clear you question. Is you wanna try to pass environment to docker container and you don't know how to use this values inside container ? Nothing wrong with your Dockerfile – Truong Dang Nov 28 '18 at 01:24
  • To clarify what Truong said: Did the environment variables not get set inside the container or was npm not able to pick up the variables? Could you please check by running echo $ – Anuvrat Parashar Nov 28 '18 at 01:28
  • 2
    Remember, IP address and host names can change, even between dev/test/prod environments in the same organization. This is not a detail you want "baked in" to a Docker image and passing it at runtime as an environment variable is far better. – David Maze Nov 28 '18 at 01:48
  • Please check this question, https://stackoverflow.com/questions/39597925/how-do-i-set-environment-variables-during-the-build-in-docker/39598751 – Ali Torki Nov 28 '18 at 07:56
  • See scope on ARG: https://docs.docker.com/engine/reference/builder/#scope – BMitch Nov 28 '18 at 12:11

1 Answers1

4

I ran your Dockerfile and myIP is indeed empty when I run env inside of the container.

To fix it, try putting the ARG line AFTER the FROM line.

So,

FROM node:11

ARG myIP

ENV myIP1 $myIP

ENV REACT_APP_MOCK_API_URL=http://${myIP1}:8080/API
ENV REACT_APP_MOCK_API_URL_AUTH=http://${myIP1}:8080/API/AUTH
ENV REACT_APP_MOCK_API_URL_PRESENTATION=http://${myIP1}:8080/API/PRESENTATION

Building using this Dockerfile, I was able to set myIP.

Rickkwa
  • 2,197
  • 4
  • 23
  • 34
  • ARG has scope. Before a FROM line, the ARG only applies to the FROM lines. In other parts of the Dockerfile, the ARG applies from where it's defined to the end of the stage (or Dockerfile in a single stage file). – BMitch Nov 28 '18 at 12:09
  • Thank you so much all. You guys are so helpful. – Ranjith Nov 28 '18 at 22:51