create-react-app icon indicating copy to clipboard operation
create-react-app copied to clipboard

How to run React app inside Docker with env vars

Open furlanrapha opened this issue 10 years ago • 46 comments

Already set the env vars in my Docker on AWS, but the app is not using it when running.

Does anyone know how I can do it?

For development, I'm using the .env file. For the build, I'm putting the .env file in .dockerignore so this development file doesn't go into the build version. My intention is to use the default Env Vars configuration in AWS ECS.

I'm not using docker-compose. I'm just using the Dockerfile.

furlanrapha avatar Oct 29 '16 00:10 furlanrapha

According to Docker's run document, you could use -e flags to set any environment variable in the container.

For example:

docker run  \
  -d \
  -e "NODE_ENV=production" \
  -e "REACT_APP_APIKEY=foObArBAz" \
  your-image-name

Then, your could get the value from process.env in your JS code:

console.log(process.env.REACT_APP_APIKEY)
// foObArBAz

jihchi avatar Oct 30 '16 14:10 jihchi

Sorry @jihchi, I will give more context here:

I'm trying to run the npm run build and set this build version for Staging and Production environment.

Since I have 2 environments, I was trying to use the AWS ECS env vars (defining it inside the Task Definition) to set the environment variables. The catch is, when I run npm run build it tries to copies the local env vars to the build version. For development, I use the .env file but I don't want to use it for creating the Docker image, so I have created a .dockerignore file to ignore the .env file. That's all working fine here. Now it is generating the build version and I saw in the minified JS the env vars as REACT_APP_APIKEY (following your example). But now when I set the env vars it looks like it doesn't get my configuration.

My final question is: when I generate the build version (with npm run build), I can't have a custom configuration to use in this build version? Or I am missing some point here? If I can't have a builde version with a custom configuration, I have to assume running the "development" version to set custom configuration?

I will attach here my Dockerfile to give a better view of the situation.

furlanrapha avatar Oct 30 '16 18:10 furlanrapha

Dockerfile

FROM node:6.3.1

# Create app directory
RUN mkdir -p /src/app
WORKDIR /src/app

# Install app dependencies
COPY package.json /src/app/
RUN npm install

# Bundle app source
COPY . /src/app

# Build and optimize react app
RUN npm run build

EXPOSE 3000

# defined in package.json
CMD [ "npm", "run", "start:server" ]

packages.json (the rest was omitted for context purposes)

...
"start:server": "http-server -p 3000 ./build",
...

furlanrapha avatar Oct 30 '16 18:10 furlanrapha

Maybe you could use ARG directive in Dockerfile.

For example, Add following code in your Dockerfile:

ARG NODE_ENV=staging
ENV NODE_ENV=$NODE_ENV

ARG REACT_APP_APIKEY=foObArBAz
ENV REACT_APP_APIKEY=$REACT_APP_APIKEY

Then, execute docker build command with additional --build-arg flags:

(Assume that you have environment variables in host machine called HOST_NODE_ENV and HOST_REACT_APP_APIKEY)

docker build \
  --build-arg NODE_ENV=$HOST_NODE_ENV \
  --build-arg REACT_APP_APIKEY=$HOST_REACT_APP_APIKEY \
  .

docker build will pass in host environment variables to your Dockerfile.

jihchi avatar Oct 31 '16 02:10 jihchi

@jihchi my intention is to use the build version with custom env vars. Looking to the build version it looks like is everything minified so I can't have a build version that I can customize the env vars for Staging and Production.

I think that what I want is not supported. I will have to probably run the development server in order to accomplish this.

furlanrapha avatar Oct 31 '16 22:10 furlanrapha

I don't know anything about Docker. Is there anything I could help you with? Do we need to fix something in Create React App, or is it just a usage question?

gaearon avatar Nov 20 '16 18:11 gaearon

So @gaearon, in Docker you generate an image and send this to the container (in my case in using AWS ECR). This image is like a build version, but I can use this image for all my environments. In my case here, we have Staging and Production environment. So I have the possibility to have the same image version of my application (0.1.0, 0.2.0, etc..) and use through the environments.

The point for create-react-app is, if I generate the Docker image using the npm run build it will try to read my env vars and I actually doesn't have it at this time (because the env vars stay on the AWS ECR). What I need would be the ability to generate the build version with the minified files but still have the ability to set the env vars to use in this build version.

I don't know if my explanation was good for your understanding and I don't know if what I want is possible to achieve since in the build version we only have static files.

furlanrapha avatar Nov 22 '16 21:11 furlanrapha

So you build the image on the local machine, then deploy it? Once it is built, you cannot add any env var to it, because CRA builds a static file. I think the best way is to serve the html with php or node backend that reads from env var to print a global variable.

viankakrisna avatar Nov 23 '16 21:11 viankakrisna

@gaearon No, for the most part docker works fine with create-react-app, however if anyone has a similar issue to this, they just need to make sure they add env_file: .env to their docker-compose.yml

lallmon avatar Nov 23 '16 21:11 lallmon

@gearon Docker is amazing, I can run create-react-app without installing node on my local, hence avoiding having to use node/npm version managers such as nvm. Plus, it just works! I would even go so far to say at the very least you should add a how to integrate with docker section to the readme.

If anyone is interested I got it to work with the following (for all steps below, replace the string boilerplate with you apps name) - if there are any improvements I can make, please let me know.

Step 1) After creating your react app with create-react-app -> cd into your newly created apps directory and run this command

docker network create boilerplate

Step 2) Add a dockerfile to the root of your app directory

Dockerfile

FROM node:6.9.4

# Prepare app directory
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app/

# Install dependencies
COPY package.json /usr/src/app/
RUN npm install --silent

ADD . /usr/src/app/

EXPOSE 3000
CMD [ "npm", "start" ]

Step 3) create a docker-compose.yml in your root directory

docker-compose.yml

version: "2"

services:
  frontend:
    container_name: "boilerplate"
    build: .
    environment:
      env_file: .env
      NODE_ENV: development
    ports:
      - '3000:3000'
    volumes:
      - .:/usr/src/app

networks:
  default:
    external:
      name: boilerplate

You can now access your app as normal at http://localhost:3000

and you can even interact with your new docker container via the following command

docker-compose run --rm boilerplate /bin/bash

Yes, this isn't following some of the nodejs docker recommend best practices, but I use the above only for the dev environment configuration so I'm unaware if those recommendations are needed. I'm open minded to improving this though.

Obviously you need to configure the build docker differently than above.

haluvibe avatar Jan 17 '17 06:01 haluvibe

@haluvibe How can I run create-react-app without having nodejs installed on my local?

cschroeter avatar Feb 02 '17 14:02 cschroeter

@cschroeter

By using Docker as he describes. Docker makes a "container" that contains system level dependencies, and executes the Node runtime inside that.

If you have a dockerized app, you could completely uninstall Node from your system, and still run the app.

lallmon avatar Feb 02 '17 21:02 lallmon

@LucasKA But I have to have NodeJS installed to create the boilerplate? That is a little disadvantage. Also if I am using Typescript, it looks up the typings files in the corresponding node_modules folder. So I am not 100% convinced how I can get rid of NodeJS during development time :/

cschroeter avatar Feb 03 '17 10:02 cschroeter

@cschroeter I can't speak for your use cases, as I don't know what boilerplate you are running and I don't use typescript.

However, a container is just that, a system level container. You can SSH into a Docker container and run commands, or set up scripts for container build or what have you.

I don't use Docker to "remove Node completely", I still keep the Current version of Node on my laptop (with all the global CLI tools).

I use docker to run my apps in as similar of an environment I am deploying to. Mostly Node 6.9.x LTS with NPM 3.10

lallmon avatar Feb 04 '17 20:02 lallmon

thanks for all the tips on this page, I've been able to get CRA running in docker. I found a few other handy things:

  • if you link port 35729 on your container to 35729 on your system, hot reloading works
  • you can watch/run all tests within docker as well with a 'test' config in docker-compose.
  • I've also created a multi-purpose docker container that will build the production version and serve it with nginx. I'm not sure if this is necessarily what I'd use in production (as the files could just be served statically via s3/CDN, but it allows me to quickly look at a production version of my app, or let me run it in a CI enviroment).

Here's my setup: Dockerfile

FROM node:6.3.1

RUN apt-get update && \
    apt-get install -y nginx

WORKDIR /src

COPY . /src

RUN npm install

CMD /bin/bash ./run.sh

run.sh (executed by the docker container)

#!/usr/bin/env bash
set -e
set -x

export NODE_ENV="${NODE_ENV:-development}"

if [ $NODE_ENV == "development" ]; then
  # this runs webpack-dev-server with hot reloading
  npm start
else
  # build the app and serve it via nginx
  npm run build
  mkdir -p $ROOT/logs/nginx
  nginx -g 'daemon off;' -c $ROOT/src/nginx.conf
  nginx -c $ROOT/src/nginx.conf
fi

NOTES: If NODE_ENV=development this will run the webpack-development-server, otherwise it will build the app and serve it via nginx. (I got this from a great blog post which I can't for the life of me find anymore)

nginx.conf

worker_processes 1;

events {
  worker_connections 1024;
}

http {
  access_log /var/log/nginx/access.log;
  error_log  /var/log/nginx/error.log;

  server {
    gzip on;
    listen 8000;
    server_name localhost;
    root /src/build;

    include /etc/nginx/mime.types;

    location /nginx_status {
      stub_status on;
      access_log off;
    }

    location / {
      try_files $uri $uri/ /index.html;
    }
  }
}

docker-compose.yml

version: '2'
services:
  dev:
    build:
      context: .
      dockerfile: Dockerfile
    image: ui-dev
    container_name: webpack-container
    environment:
      - NODE_ENV=development
    ports:
      - "8080:3000"
      - "35729:35729"
    volumes:
      - .:/src
      - /src/node_modules
  test:
    build:
      context: .
      dockerfile: Dockerfile
    image: ui-test
    container_name: webpack-test-container
    environment:
      - NODE_ENV=test
    volumes:
      - .:/src
      - /src/node_modules
    command: npm test
  prod:
    build:
      context: .
      dockerfile: Dockerfile
    image: guest-ui-prod
    container_name: prod-container
    environment:
      - NODE_ENV=production
    ports:
      - "8000:8000"
    volumes:
      - /src/node_modules

For my development with hot reloading, I run one terminal window and execute the following: docker-compose up -d dev

To watch and run tests, I then open another terminal windown and execute: docker-compose up test (I don't use the -d flag as I want to see the output)

And for a production sanity check, I can run docker-compose up prod NOTE: - this will serve the react app at the time the docker image was created, so if you've been making changes since the docker build, these won't appear. However, if this is used as part of a CI system which checks out the code and builds it, the image built will be the latest.

On an unrelated note, I also found it useful to set the NODE_PATH in my package.json to allow relative imports:

  "scripts": {
    "start": "NODE_PATH=./src/ react-scripts start",
    "build": "NODE_PATH=./src/ react-scripts build",
   ...
  }

baxford avatar Feb 06 '17 02:02 baxford

@furlanrapha Did you have your problem solved? Thanks advices

jayhuang75 avatar Feb 07 '17 16:02 jayhuang75

No @jayhuang75, I'm still doing npm install and running the development server in the Docker image so I can have the env vars set in AWS Task Definition.

furlanrapha avatar Feb 07 '17 16:02 furlanrapha

@haluvibe your Docker configuration looks good. Solely creating additional network seems unneccessary, because by default Docker Compose sets up a network for you:

By default Compose sets up a single network for your app. Each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

Also in order to enable livereload feature on Windows host, you have to enable chokidar polling, because of inotify does not work on Docker for Windows. Here I shared my experience and how I made it working on Windows.

jordan-enev avatar Mar 28 '17 09:03 jordan-enev

@furlanrapha I have had a very similar issue, and I was able to sucessfully fix it. I am using webpack to do the "build", and I am able to access all environment variables inside my react app.

Can you please tell me how do you do your builds ? I might be able to help.

daveamit avatar Apr 14 '17 13:04 daveamit

@daveamit you ejected your app from react-scripts?

Here is the Dockerfile that I use today (we don't use docker-compose):

FROM node:6.9.4

EXPOSE 3000
CMD [ "npm", "run", "start" ]

WORKDIR /src/app

# Install app dependencies
COPY npm-shrinkwrap.json .
COPY package.json .
RUN npm install

COPY public ./public
COPY src ./src

furlanrapha avatar Apr 14 '17 14:04 furlanrapha