0

I have a react app built with webpack that I want to deploy inside a docker container. I'm currently using the DefinePlugin to pass the api url for the app along with some other environment variables into the app during the build phase. The relevant part of my webpack config looks something like:

plugins: [
    new DefinePlugin({
        GRAPHQL_API_URL: JSON.stringify(process.env.GRAPHQL_API_URL),
        DEBUG: process.env.DEBUG,
        ...
    }),
    ...
]

Since this strategy requires the environment variables at build time, my docker file is a little icky, since I need to actually put the webpack build call as part of the CMD command:

FROM node:10.16.0-alpine

WORKDIR /usr/app/

COPY . ./

RUN npm install

# EXPOSE and serve -l ports should match
EXPOSE 3000
CMD npm run build && npm run serve -- -l 3000

I'd love for the build step in webpack to be a layer in the docker container (a RUN command), so I could potentially clean out all the source files after the build succeeds, and so start up is faster. Is there a standard strategy for dealing with this issue of using information from the docker environment when you are only serving static files?

Rob Allsopp
  • 3,309
  • 5
  • 34
  • 53

1 Answers1

0

How do I use environment variables in a static site inside docker?

This question is broader than your specific problem I think. The generic answer to this is, you can't, by nature of the fact that the content is static. If you need the API URL to be dynamic and modifiable at runtime then there needs to be some feature to support that. I'm not familiar enough with webpack to know if this can work but there is a lot of information at the following link that might help you.

Passing environment-dependent variables in webpack

Is there a standard strategy for dealing with this issue of using information from the docker environment when you are only serving static files?

If you are happy to have the API URL baked into the image then the standard strategy with static content in general is to use a multistage build. This generates the static content and then copies it to a new base image, leaving behind any dependencies that were required for the build.

https://docs.docker.com/develop/develop-images/multistage-build/

peterevans
  • 34,297
  • 7
  • 84
  • 83