Skip to main content

Friday, April 12, 2024

· One min read

Docker Build Args vs Runtime Env Variables: Optimizing Frontend Deployment

During the building stage, environment variables are passed as arguments to the Docker image, influencing the build process. Then, during container execution, environment variables are set within the running container, ensuring customization without the need for rebuilding the image each time the application is spun up.

FROM mhart/alpine-node:10
ARG NODE_ENV
ENV NODE_ENV $NODE_ENV
ADD . /app
WORKDIR /app

# install dependencies
COPY app/package.json app/package-lock.json ./
RUN npm install
RUN yarn build

EXPOSE 7000

CMD ["yarn", "start"]
build:
context: .
dockerfile: Dockerfile-preprod
args:
- NODE_ENV=${NODE_ENV}

The use case is:

For frontend apps, building into either page or static formats is standard, followed by client-side execution. To customize with env variables, like server addresses for dev or prod, they're set during building. Avoiding rebuilding for every runtime spin-up ensures swift deployment.

https://stackoverflow.com/questions/52429984/docker-compose-build-environment-variable