首页 > 解决方案 > Angular 与 nginx 无法与后端通信(Golang)

问题描述

我正在使用 nginx 来提供 angular(index.html) 并且效果很好。问题是我在尝试与后端通信时不断出错。

我的 NGINX + Angular Dockerfile

FROM node:12-alpine as builder
WORKDIR /usr/src/app
COPY . .
RUN npm install --silent
RUN npm run ng build --prod

FROM nginx:latest

COPY --from=builder /usr/src/app/dist/FrontEnd /var/www
COPY ./default.conf /etc/nginx/nginx.conf

EXPOSE 80

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

我的 Golang Dockerfile

FROM golang:latest

ENV GO111MODULE=on
RUN mkdir /app
WORKDIR /app

COPY go.mod .
COPY go.sum .
RUN go mod download

COPY . .

RUN go build main.go

EXPOSE 8000

CMD [ "./main" ]

我的 Docker-compose

version: '3.7'
services:
    postgres:
      image: "postgres:latest"
      restart: always
      volumes:
        - ./init.sql:/docker-entrypoint-initdb.d/init.sql
        - data:/var/lib/postgresql/data
      ports:
        - "5432:5432"
      environment:
        - POSTGRES_DB=Project
        - POSTGRES_USER=postgres
        - POSTGRES_PASSWORD=password
      networks:
        - mynet

    #Back-end
    golang:
      build:
        context: .
        dockerfile: Dockerfile
      container_name: golang
      links:
        - postgres  
      ports:
        - "8000:8000"
      networks:
        - mynet
    
    #Front-end Angular Application
    angular:
      links:
        - golang
      build:
        context: ./FrontEnd
        dockerfile: Dockerfile
      environment:
        - host=golang
      ports:
        - "4200:80"
      networks:
        - mynet

volumes:
  data:

networks:
  mynet:
    driver: bridge

我的 nginx default.conf

worker_processes 4;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        root   /var/www;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location /users {
            proxy_pass http://golang:8000;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
        }
    }
}

这是我尝试向 golang [1] 发送 api 调用时的结果:https ://i.stack.imgur.com/XQuhf.png

我已经被这个问题困扰了好几天了,而且时间不多了。请帮忙!提前致谢。

标签: angulardockergonginxdocker-compose

解决方案


golang:8000只能在 docker 网络中访问。您可以通过在浏览器中访问来检查您的 golang API ,并在您的角度代码中http://35.238.xx.xx:4200/users/xxx使用相对 url 。"/users/xxx"


推荐阅读