I am trying to set my Docker image environment variables conditionally based on argument passed while building the docker image. Here is what my docker file looks like
# pull the base image
FROM node:alpine as build
# set the working direction
WORKDIR /app
# add `/app/node_modules/.bin` to $PATH
ENV PATH /app/node_modules/.bin:$PATH
# install app dependencies
COPY package.json ./
COPY yarn.lock ./
RUN yarn
# add app
COPY . ./
# define environment variables
ARG REACT_APP_BASE_URL=https://service.dev.localhost.com
ARG REACT_APP_SERVICES_BASE_URL=https://services.dev.localhost.com
ARG REACT_APP_BASE_URL_PROD=https://service.localhost.com
ARG REACT_APP_SERVICES_BASE_URL_PROD=https://services.localhost.com
ARG app_env
ENV app_stage $app_env
ENV REACT_APP_BASE_URL=$REACT_APP_BASE_URL
ENV REACT_APP_SERVICES_BASE_URL=$REACT_APP_SERVICES_BASE_URL
ENV REACT_APP_BASE_URL_PROD=$REACT_APP_BASE_URL_PROD
ENV REACT_APP_SERVICES_BASE_URL_PROD=$REACT_APP_SERVICES_BASE_URL_PROD
RUN if ["$app_stage" = "dev"]; then \
echo "REACT_APP_BASE_URL=$REACT_APP_BASE_URL" > .env; \
echo "REACT_APP_WALLET_BASE_URL=$REACT_APP_WALLET_BASE_URL" > .env; \
echo "REACT_APP_TRANSACTION_BASE_URL=$REACT_APP_TRANSACTION_BASE_URL" > .env; \
else \
echo "REACT_APP_BASE_URL=$REACT_APP_BASE_URL_PROD" > .env; \
echo "REACT_APP_WALLET_BASE_URL=$REACT_APP_WALLET_BASE_URL_PROD" > .env; \
echo "REACT_APP_TRANSACTION_BASE_URL=$REACT_APP_TRANSACTION_BASE_URL_PROD" > .env; \
fi
CMD ["yarn", "start"]
Here I am setting environment variables to production or development based on app_env
when I run my docker build command.
This is the command I run to build image
For production
docker build --build-arg app_env=production -t app-prod .
and for dev docker build --build-arg app_env=dev -t app-dev .
And then I run the app using
docker run \
-it \
--rm \
-v {$PWD}:/app \
-v /app/node_modules \
-p 5000:3000 \
-e CHOKIDAR_USEPOLLING=true \
app-dev
It seems that the environment variables are not set conditionally because no matter what image I run prod
or dev
, the environment variables point to dev
.
How do I fix this?