Py学习  »  docker

Docker+Nginx解决跨域发布Vue项目到生产环境

袁志健 • 4 年前 • 354 次点击  
阅读 13

Docker+Nginx解决跨域发布Vue项目到生产环境

前言

使用vue-cli脚手架构建的vue工程在开发时可以使用

npm run server
复制代码

愉快地进行开发,遇到后端接口需要跨域访问时使用 devServer.proxy完成代理配置即可。

代理配置

如何将工程打包发布到生产环境呢?

下面将采用Docker+Nginx的方法完成前端项目的发布,并使用Nginx反向代理完成跨域支持。

增加Dockerfile文件到项目根目录

Dockerfile

内容如下:

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 和其他中间构建产物被复制到镜像中导致构建问题。

增加Nginx配置文件文件到项目根目录

nginx.conf

内容如下:

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;
    }
  }
}
复制代码

编译镜像

打开终端执行

docker build . -t my-app
复制代码

编译镜像

运行镜像

docker run -d -p 8080:80
复制代码

浏览器访问

http://localhost:8080/
复制代码

访问结果

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50422
 
354 次点击