Contents

Vue App Runtime에 환경변수 전달하기(k8s configmap)

기존에 배포 버전별로 이미지를 생성(config 변수를 이미지 안에 저장) 하던 프로젝트를, 이미지를 단일화 하고 k8s configmap을 통해 변수를 활용하게 되었습니다.
vue.env에서 configmap으로 옮기는 방법입니다.

0. 요약

  • configmap에 변수를 리턴하는 config.js 파일을 저장
  • config.js 을 web root 디렉토리에 마운트
  • index.html에서 config.js를 로드하여 global 변수로 사용

1. Config 파일 생성

public/config.js를 파일을 생성 합니다.

const config = (() => {
  return {
    "VUE_CONFIG_APP_API": "...",
  };
})();

2. index.html 수정

public/index.html 수정

 <!-- docker configurable variables -->
  <script src="<%= BASE_URL %>config.js"></script>

3. ESLint

.eslintrc.js나 package.json의 eslintConfig 수정

3.1 .eslintrc.js

  globals: {
    config: "readable",
  },

3.2 package.json

  "eslintConfig": {
    "globals": {
      "config": "readable"
    }
  },

4. Config 적용

export const actions = {
  async LoadUsers({ dispatch }) {
    return await dispatch(
      "axios/get",
      {
        url: config.VUE_CONFIG_APP_API + "User/List",
      },
      { root: true }
    );
  }

5. Configmap

configmap.yaml 생성 or config.js 추가

apiVersion: v1
kind: ConfigMap
metadata:
  name: fe-config
  namespace: ...
data:
  config.js: |
    var config = (() => {
      return {
        "VUE_CONFIG_APP_API": "...",
      };
    })();    

6. Deployment

deployment.yaml 수정

Volume에 Configmap을 추가하고, Volumemount에 config.js를 web root에 추가합니다.

apiVersion: apps/v1
kind: Deployment
metadata:
  ...
spec:
  ...
  template:
    ...
    spec:
      volumes:
        - name: config-volume
          configMap:
            name: fe-config
      containers:
        - ...
          volumeMounts:
                - name: config-volume
                  mountPath: /usr/share/nginx/html/config.js
                  subPath: config.js

Reference