[英]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
流量轉發到Service
: kubectl 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.