我的前端应用程序在 NGINX 之后,它在 docker 容器中提供静态前端文件(用 Angular 编写),通信端口是 80:80。
我的后端应用程序是 NestJS,它在另一个 docker 容器中的端口 localhost:3000 上提供数据。
使用 docker-compose up 启动应用程序,但我的前端无法到达后端 - 出现 502,错误的 GW。
问题是由 nginx 或 docker-compose.yml 或两者的设置引起的吗?
Dockerfile 前端:
FROM node:latest AS builder
WORKDIR /app
COPY . .
ARG configuration=production
RUN npm install && npm run build.prod
FROM nginx:latest
LABEL version="1.0"
COPY nginx.conf /etc/nginx/nginx.conf
WORKDIR /usr/share/nginx/html
COPY --from=builder /app/dist/frontend/ .
Dockerfile 后端:
FROM node:10 AS builder
WORKDIR /app
COPY ./package.json ./
RUN npm install
COPY . .
RUN npm run build
ADD . /app
EXPOSE 3000
CMD ["npm", "run", "start:prod"]
NGINX.conf
worker_processes 1;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
include /etc/nginx/mime.types;
gzip on;
gzip_min_length 1000;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;
location / {
try_files $uri $uri/ /index.html;
}
location /api {
proxy_pass http://127.0.0.1:3000;
}
location ~ \.html$ {
add_header Cache-Control "private, no-cache, no-store, must-revalidate";
add_header Expires "Sat, 01 Jan 2000 00:00:00 GMT";
add_header Pragma no-cache;
}
}
}
docker-compose.yml
version: '3'
services:
angular:
image: "docker-frontend:v3"
container_name: "frontend"
ports:
- "80:80"
links:
- restapi
restapi:
image: "docker-backend:v1"
container_name: "backend"
expose:
- 3000
ports:
- "3000:3000"
最佳答案
您不能在容器内使用本地主机连接到另一个容器,为此您可以使用容器的名称
例如
http://localhost:3000/api/
会是
http://backend:3000/api/
关于angular - 前端无法到达单独的 docker 容器中的后端端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60192777/