You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker部署的Vite+React应用无法通过K8s Pod IP访问问题求助

问题排查与解决步骤

1 修复Vite访问限制

你当前使用Vite开发服务器启动的场景下,访问非本地地址出现空白/无响应,是因为Vite默认开启了主机访问校验,仅允许localhost、127.0.0.1等本地地址访问,容器IP、K8s集群内IP都不在默认允许列表中。
修改vite.config.js的server配置即可解决:

server: {
  watch: {
    usePolling: true,
  },
  open: false,
  host: '0.0.0.0',
  // 新增配置,允许所有主机访问,仅开发模式生效,不影响生产构建
  allowedHosts: true,
  // 固定端口,避免默认端口发生变化
  port: 3000
}

2 修正K8s访问方式

你配置的Service为NodePort类型,ClusterIP(10.106.213.128)仅支持在K8s集群内部访问,集群外部访问需要使用任意集群节点的IP+NodePort端口31000,访问地址格式为http://[节点IP]:31000。
如果需要验证集群内部服务是否正常,可以进入集群内任意Pod,执行curl http://10.106.213.128:3000查看是否返回正确的页面内容。

3 生产环境部署优化(推荐)

你当前的部署方式是将Vite开发服务器直接打包运行,仅适用于本地开发调试,完全不符合生产环境要求:开发服务器性能差、无静态资源缓存策略、安全性低。生产环境应该先构建出静态资源,再用Nginx/Caddy等专业Web服务器托管。

3.1 替换为多阶段构建Dockerfile

# 构建阶段:用node镜像编译静态资源
FROM node:latest AS builder
WORKDIR /usr/src/app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build

# 运行阶段:用轻量nginx镜像托管静态资源
FROM nginx:alpine
# 复制构建产物到nginx默认静态资源目录
COPY --from=builder /usr/src/app/dist /usr/share/nginx/html
# 单页应用可选:复制自定义nginx配置,解决前端路由刷新404问题
# COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

单页应用对应的nginx配置参考:

server {
    listen       80;
    server_name  localhost;
    root   /usr/share/nginx/html;
    index  index.html index.htm;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

3.2 调整K8s配置

匹配nginx的80端口,修改Deployment和Service配置:

kind: Deployment
apiVersion: apps/v1
metadata:
  name: hello-world-app-frontend
spec:
  replicas: 2
  selector:
    matchLabels:
      app: hello-world-app-frontend
  template:
    metadata:
      labels:
        app: hello-world-app-frontend
    spec:
      containers:
        - name: hello-world-app-frontend
          image: hello-world-app-frontend
          imagePullPolicy: Never
          ports:
            - containerPort: 80
      restartPolicy: Always
---
kind: Service
apiVersion: v1
metadata:
  name: hello-world-app-frontend
spec:
  type: NodePort
  ports:
    - port: 80
      targetPort: 80
      protocol: TCP
      nodePort: 31000
  selector:
    app: hello-world-app-frontend

内容的提问来源于stack exchange,提问作者mrks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 18:06:04