DEV Community

Cover image for Environment Variables Specified in docker-compose.yml Not Accessible During Container Build
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Environment Variables Specified in docker-compose.yml Not Accessible During Container Build

This article was originally published on bmf-tech.com.

Overview

I specified an env_file for one of the services in docker-compose.yml to set environment variables, but they were not accessible within the container being built (on the Dockerfile side). I was building a Vue application inside the container using npm and wanted the application to reference environment variables during the build process in the form of process.env.VUE_APP_API_ENDPOINT.

Solution

The env_file and environment keys specified in docker-compose.yml become accessible after the container is built, so using these keys alone does not allow access during the container build.

The solution was to specify the args key in docker-compose.yml and pass variables to the container.

.env

VUE_APP_API_ENDPOINT="http://gobel-api.local"
Enter fullscreen mode Exit fullscreen mode

Dockerfile

FROM node:14.3.0-alpine as build-stage

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

# Accept arguments and define environment variables inside the container
ARG VUE_APP_API_ENDPOINT
ENV VUE_APP_API_ENDPOINT=${VUE_APP_API_ENDPOINT}

# Build the application. Environment variables can be referenced.
RUN npm run local-build

FROM nginx:1.19.0-alpine

COPY ./nginx/nginx.conf /etc/nginx/nginx.conf
COPY ./nginx/conf.d/gobel-admin-client.conf /etc/nginx/conf.d/gobel-admin-client.conf
COPY --from=build-stage /app/dist /var/www/html
Enter fullscreen mode Exit fullscreen mode

docker-compose.yml

version: "3.8"
services:
  app:
    container_name: "gobel-admin-client"
    # Load environment variables from a file
    env_file: ".env"
    build:
        context: "./app"
        dockerfile: "Dockerfile"
        # Pass variables during container build
        args:
          VUE_APP_API_ENDPOINT: $VUE_APP_API_ENDPOINT
    ports:
      - "82:80"
    networks:
      - gobel_link
networks:
    gobel_link:
        external: true
Enter fullscreen mode Exit fullscreen mode

For reference, here is the application code that needs to reference environment variables during the build.

const apiClient = axios.create({
  baseURL: process.env.VUE_APP_API_ENDPOINT,
  headers: {
    "Content-Type": "application/json"
  },
  responseType: "json"
});
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)