前端无法到达单独的Docker容器中的后端端口

时间:2020-02-12 16:20:26

标签: angular docker docker-compose containers nestjs

我的前端应用程序位于NGINX后面,后者在Docker容器中提供静态前端文件(以Angular编写),通信端口为80:80。

我的后端应用程序是NestJS,它在另一个Docker容器中的端口localhost:3000上提供数据。

使用docker-compose启动应用程序,但我的前端无法到达后端-获取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"

1 个答案:

答案 0 :(得分:4)

您不能在容器内部使用localhost连接到另一个容器,以实现可以使用容器的名称

例如

http://localhost:3000/api/

将会

http://backend:3000/api/