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

Kubernetes中配置Echo Pod使用非80端口失败问题排查

问题根源:你误解了containerPort的作用!

哦,我太懂这种困惑了——你明明在Pod的YAML里把containerPort设成了81,但测试下来只有80端口能连上,81端口一直报连接拒绝。其实问题出在**containerPort根本不是用来修改容器内部应用监听端口的**!

这个字段只是Kubernetes的一个"声明性"标记:告诉集群“这个容器对外暴露了这个端口”,方便后续Service或者端口转发的时候识别,但它完全不会改变容器里应用本身的配置。你用的是官方nginx镜像,默认情况下nginx就是监听80端口的,所以不管你YAML里写81还是别的,容器里的服务还是在80跑,这就是为什么80能连,81连不上。

解决办法:让nginx真正监听81端口

要解决这个问题,你得从容器内部的应用配置下手,让nginx实际去监听81端口,再配合Kubernetes的配置保持一致。下面给你两种常用方案:

方案一:用ConfigMap挂载自定义nginx配置

这种方式不用改镜像,适合快速测试:

  1. 先写一个自定义的nginx配置文件(比如叫nginx.conf),让它监听81端口:
events {}
http {
    server {
        listen 81;
        location / {
            default_type text/plain;
            return 200 "Hello from nginx on port 81!\n";
        }
    }
}
  1. 在echo命名空间创建ConfigMap来存储这个配置:
kubectl create configmap nginx-custom-config --namespace=echo --from-file=nginx.conf
  1. 修改你的Pod YAML,把ConfigMap挂载到容器里替换默认的nginx配置:
apiVersion: v1
kind: Pod
metadata:
  name: echo-pod
  namespace: echo
spec:
  containers:
  - name: nginx
    image: nginx
    ports:
    - containerPort: 81
    volumeMounts:
    - name: nginx-config-volume
      mountPath: /etc/nginx/nginx.conf
      subPath: nginx.conf  # 只挂载单个文件,不覆盖整个目录
  volumes:
  - name: nginx-config-volume
    configMap:
      name: nginx-custom-config

方案二:构建自定义nginx镜像

如果需要长期使用这个配置,构建自己的镜像更方便:

  1. 准备Dockerfile和刚才的nginx.conf:
FROM nginx:latest
COPY nginx.conf /etc/nginx/nginx.conf
  1. 构建并推送镜像(替换成你的镜像仓库地址):
docker build -t your-registry/my-nginx:port81 .
docker push your-registry/my-nginx:port81
  1. 修改Pod YAML使用这个自定义镜像:
apiVersion: v1
kind: Pod
metadata:
  name: echo-pod
  namespace: echo
spec:
  containers:
  - name: nginx
    image: your-registry/my-nginx:port81
    ports:
    - containerPort: 81
验证一下

重新创建Pod后,再用busybox测试:

kubectl exec busybox -- telnet 192.168.211.1 81

这时候应该就能成功连接上81端口啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 10:57:42