angular - 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
我已经被这个问题困扰了好几天了,而且时间不多了。请帮忙!提前致谢。
解决方案
golang:8000
只能在 docker 网络中访问。您可以通过在浏览器中访问来检查您的 golang API ,并在您的角度代码中http://35.238.xx.xx:4200/users/xxx
使用相对 url 。"/users/xxx"
推荐阅读
- c# - 为什么C#中读取文本文件用的是绝对路径,而且路径会变
- wordpress - WP“retrieve_password_message”
- linux - 如何在容器 runc 中使用 LD_PRELOAD
- javascript - 选择获取数据属性值并嵌入为选择选项
- cytoscape - Astray cytoscape 将浮点值识别为整数
- unity3d - Raycast 在 start 方法中不起作用,但在 fixupdate 方法中使用相同的代码
- java - 使用 Java 11 和 Spring Boot 调用 java.net.http.HttpClient 的响应不可靠
- javascript - 如何使用谷歌脚本从列表中返回另一个列表中不存在的值
- javascript - Adding child element to a parent element using javascript
- linux - Modifying a particular line in a text file from the command-line