nginx从8080端口重定向到5000端口

时间:2020-04-10 22:23:20

标签: docker nginx docker-compose axios

我有dockerized vue.js应用程序。这是我的Dockerfile

# build
FROM node:lts-alpine as build-stage
RUN apk update && apk add git
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# production (production-stage)
FROM nginx:stable-alpine as production-stage
COPY --from=build-stage /app/dist /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/*
COPY nginx/api.conf /etc/nginx/conf.d/
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

在将HTTP请求(在axios的帮助下)发送到API之前,我的拦截器http.js帮助程序将重写路径。像这样,从/path/to/method/api/path/to/method/

import axios from 'axios';

const http = axios.create({
  headers: {
    'content-type': 'application/json',
  },
  baseURL: '/api/'
});

http.interceptors.request.use(
  function(config) {
    return config;
  },
  function(error) {
    return Promise.reject(error);
  }
);

http.interceptors.response.use(
  function(response) {
    return response;
  },
  function(error) {
    return Promise.reject(error);
  }
);

export default http;

因此,我尝试通过nginx.conf文件捕获此API位置。在这里。

server {
  listen 80;
  charset utf-8;
  client_max_body_size 10M;

  location /api/ {
      proxy_pass http://localhost:5000/;

      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
  }

  location / {
    root /usr/share/nginx/html;
    try_files $uri $uri/ /index.html;
  }

  error_page   500 502 503 504  /50x.html;
}

但是此nginx位置无法捕获我对API的响应。 期望我的http请求是http://localhost:5000/api/path/to/method,但我的http请求是http://localhost:8080/api/path/to/method,分别是响应的返回状态为500的对象。因为在该端口上,我没有后端docker容器。我也有docker-compose.yml文件:

version: '3.7'

services:

  frontend:
    build: .
    ports:
      - 8080:80

使用命令docker-compose up --build -b运行我的Docker容器。我该如何解决这个问题?

0 个答案:

没有答案