首页 > 解决方案 > 在运行时使用 docker 设置 vueJS 环境变量

问题描述

所以这是我的问题,我必须对我的 vue 应用程序进行 dockerize 才能在 kubernetes/rancher 环境中使用它。

我想在我的牧场主中设置一些环境变量,例如 API 基本 url,但我不知道该怎么做。

这是我的 dockerFile:

FROM nginx:stable-alpine
# define 'app'
WORKDIR /app

COPY dist /usr/share/nginx/html

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

.gitlab-ci.yml

image: node:lts-alpine

stages:
- install
- tests
- build
- deploy-docker
- rerun-docker

cache:
  paths:
    - node_modules/

install:
  stage: install
  script: npm install
  tags: [ docker ]

test:
  stage: tests
  script: npm run test:unit
  tags: [ docker ]

build:
  stage: build
  script: npm run build
  artifacts:
    paths:
    - dist
  tags: [ docker ]

build_image:
  stage: deploy-docker
  image: //myurl//
  script:
  - docker build -t //myurl// .
  - docker push //myurl//
  only:
  - develop
  - feat/CI-front
  tags: [ docker ]

rerun:
  stage: rerun-docker
  image: //adress///kubectl:latest
  script:
  - kubectl scale deployment //myproject// --replicas=0 -n //name//
  - kubectl scale deployment //myproject// --replicas=1 -n //name//
  only:
  - develop
  - feat/CI-front
  tags: [ docker ]


如果有必要,还有我的 .env

VUE_APP_API_BASE_URL = hello

非常感谢

标签: dockervue.jsnginxenvironment-variablesrancher

解决方案


我找到了答案

码头文件:

FROM openresty/openresty
# define 'app'
WORKDIR /app

COPY dist /usr/local/openresty/nginx/html/
COPY nginx.conf /usr/local/openresty/nginx/conf/nginx.conf

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

Nginx 配置文件

worker_processes 1;

events {
  worker_connections 1024;
}

env VUE_APP_API_BASE_URL;

http {
  include mime.types;
  default_type application/octet-stream;

  gzip on;
  gzip_disable "msie6";

  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_min_length 256;
  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/vnd.ms-fontobject application/x-font-ttf font/opentype image/svg+xml image/x-icon application/javascript image/webp;

  server {
    server_name localhost;

    location / {
      root /usr/local/openresty/nginx/html;
      index index.html;
      set_by_lua $api_url 'return os.getenv("VUE_APP_API_BASE_URL")';
      sub_filter_types *;
      sub_filter '[[VUE_APP_API_BASE_URL]]' '$api_url';
      sub_filter_once off;
      try_files $uri $uri/ /index.html;
    }
  }
}

.env

VUE_APP_API_BASE_URL = [[VUE_APP_API_BASE_URL]]


推荐阅读