mszan
mszan

Reputation: 558

React not reading docker-compose environment variable

I want to set environment variables for React during docker image build. After setting up docker compose, React returns undefined as a result of:

console.log(process.env.REACT_APP_EMAILJS_USERID);

I confirmed that the running container sees the environment variable:

» docker exec -it mszan-portfolio-prod /bin/sh
/app # echo $REACT_APP_EMAILJS_USERID
foo

Commands

REACT_APP_EMAILJS_USERID=foo docker-compose -f docker-compose.production.yml build
REACT_APP_EMAILJS_USERID=foo docker-compose -f docker-compose.production.yml up

Files

docker-compose.production.yml

services:
  react:
    container_name: mszan-portfolio-prod
    restart: always
    build:
      context: .
      dockerfile: Dockerfile.production
      args:
        - REACT_APP_EMAILJS_USERID=${REACT_APP_EMAILJS_USERID}
    command: serve -s out -l 3000
    ports:
      - 4050:3000

Dockerfile.production

FROM node:lts-alpine

WORKDIR /app

ENV PATH /app/node_modules/.bin:$PATH

ARG REACT_APP_EMAILJS_USERID

ENV REACT_APP_EMAILJS_USERID $REACT_APP_EMAILJS_USERID

COPY package.json /app/

RUN npm install -g serve

RUN npm install

COPY ./ /app/

RUN npm run build

Project structure

├── Dockerfile.production
├── docker-compose.production.yml
├── node_modules
├── package.json
├── pages
├── public
├── src
└── yarn.lock

Upvotes: 0

Views: 506

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5814

You should change your build command like this:

docker-compose -f docker-compose.production.yml build --build-arg REACT_APP_EMAILJS_USERID=foo 

Then you can simply run your services using:

docker-compose -f docker-compose.production.yml up

Upvotes: 1

Related Questions