繁体   English   中英

如何访问在同一个 Pod 中运行的 NodeJS 服务器?

[英]How to access NodeJS server that is running in the same pod?

我正在尝试将应用程序部署到 Kubernetes。 我有 2 个容器:由 nginx 托管的 Angular 应用程序和 Node.js 服务器。 我在同一个 pod 中运行这些容器。 问题是 Angular 应用程序无法访问 Node.js api。 这是我的 nginx 的 default.conf:

server {
    listen 80;
    server_name localhost;

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

    location /api/ {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
    }
}

这是我的 Angular 应用程序的 Dockerfile:

FROM node:lts-alpine AS build

WORKDIR /app
COPY . .

RUN npm install

RUN npm run build:prod

FROM nginx:stable-alpine

COPY nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=build /app/dist/mag-ui /usr/share/nginx/html

这是我在 Kubernetes 集群上运行的 deploy.yml:

kind: Namespace
metadata:
  name: mag
---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: mag
  name: mag
  labels:
    app: mag
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mag
  minReadySeconds: 10
  strategy:
    type: RollingUpdate
    rollingUpdate:
      maxUnavailable: 1
      maxSurge: 1
  template:
    metadata:
      labels:
        app: mag
    spec:
      terminationGracePeriodSeconds: 10
      containers:
      - name: mag-api
        image: mag-api
        imagePullPolicy: "Always"
        ports:
        - containerPort: 3000
      - name: mag-ui
        image: mag-ui
        imagePullPolicy: "Always"
        ports:
        - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  namespace: mag
  name: mag-svc
  labels:
    app: mag
spec:
  ports:
  - port: 80
    name: ui
    targetPort: 80
  selector:
    app: mag

因此,当我将其部署到本地集群(并转发 service/mag-svc 的端口 8080:80)并浏览 localhost:8080 时,ui 应用程序尝试从 Node.js 服务器查询数据并失败: GET http://localhost:3000/api/mag/models net::ERR_CONNECTION_REFUSED

但是,如果我连接到 Angular 应用程序容器的外壳并卷曲localhost:3000/api/mag/models ,它工作正常并且我得到预期的响应。

看起来它试图访问我的主机虚拟机的 localhost,而不是运行 Angular 应用程序的容器的 localhost。 那么,如何让 Angular 应用调用 Node.js api,运行在同一个 pod 中呢?

angular在您的浏览器中运行,因此从浏览器中运行的应用程序到http://localhost:3000的连接将连接到您 PC 的localhost:3000

您可以为nodejs容器创建一个Service

apiVersion: v1
kind: Service
metadata:
  namespace: mag
  name: mag-svc-api
  labels:
    app: mag
spec:
  ports:
  - port: 3000
    name: mag-api
    targetPort: 3000
  selector:
    app: mag

...然后将localhost:3000流量转发到Servicekubectl port-forward -n mag mag-svc-api 3000:3000 从浏览器中运行的应用程序到http://localhost:3000将被转发到Service -> container running in Kubernetes

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM