Docker+Nginx解決跨域發佈Vue項目到生產環境

前言

使用vue-cli腳手架構建的vue工程在開發時可使用html

npm run server
複製代碼

愉快地進行開發,遇到後端接口須要跨域訪問時使用 devServer.proxy完成代理配置便可。 前端

代理配置

如何將工程打包發佈到生產環境呢?vue

下面將採用Docker+Nginx的方法完成前端項目的發佈,並使用Nginx反向代理完成跨域支持。node

增長Dockerfile文件到項目根目錄

Dockerfile

內容以下:nginx

FROM node:latest as build-stage
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY ./ .
RUN npm run build

FROM nginx as production-stage
RUN mkdir /app
COPY --from=build-stage /app/dist /app
COPY nginx.conf /etc/nginx/nginx.conf
複製代碼

增長.dockerignore文件到項目根目錄

.dockerignore

**/node_modules
**/dist
複製代碼

設置 .dockerignore 文件能防止 node_modules 和其餘中間構建產物被複制到鏡像中致使構建問題。vue-cli

增長Nginx配置文件文件到項目根目錄

nginx.conf

內容以下:docker

user  nginx;
worker_processes  1;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;
events {
  worker_connections  1024;
}
http {
  include       /etc/nginx/mime.types;
  default_type  application/octet-stream;
  log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
  access_log  /var/log/nginx/access.log  main;
  sendfile        on;
  keepalive_timeout  65;
  server {
    listen       80;
    server_name  localhost;
    location / {
      root   /app;
      index  index.html;
      try_files $uri $uri/ /index.html;
    }

    # 代理配置,解決跨域問題 
    location /auth {
        proxy_pass http://36.155.113.204:19999;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
      root   /usr/share/nginx/html;
    }
  }
}
複製代碼

編譯鏡像

打開終端執行npm

docker build . -t my-app
複製代碼

編譯鏡像

運行鏡像

docker run -d -p 8080:80
複製代碼

瀏覽器訪問json

http://localhost:8080/
複製代碼

訪問結果
相關文章
相關標籤/搜索