在 CentOS 上部署的 Kubernetes(k8s)中,“暴露服务”通常指让 集群外部 能访问集群内的应用。下面按常用方式 + 示例系统说明。
K8s 暴露服务主要靠 Service,常见类型:
| 类型 | 适用场景 | 外部可访问 |
|---|---|---|
| ClusterIP | 集群内部通信 | ❌ |
| NodePort | 测试 / 简单暴露 | ✅(端口范围 30000-32767) |
| LoadBalancer | 云环境 / 外部负载均衡 | ✅ |
| Ingress | HTTP/HTTPS 统一入口 | ✅(推荐生产) |
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx
spec:
replicas: 2
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx
ports:
- containerPort: 80
kubectl expose deployment nginx \
--type=NodePort \
--port=80 \
--target-port=80
或 YAML:
apiVersion: v1
kind: Service
metadata:
name: nginx
spec:
type: NodePort
selector:
app: nginx
ports:
- port: 80
targetPort: 80
nodePort: 30080
http://<NodeIP>:30080
⚠️ CentOS 注意
# 开放防火墙
firewall-cmd --add-port=30080/tcp --permanent
firewall-cmd --reload
云厂商自动支持,裸机需 MetalLB
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.13.10/manifests/namespace.yaml
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.13.10/manifests/metallb.yaml
apiVersion: metallb.io/v1beta1
kind: IPAddressPool
metadata:
name: default
namespace: metallb-system
spec:
addresses:
- 192.168.1.200-192.168.1.210
spec:
type: LoadBalancer
访问:
http://<分配的IP>
kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/baremetal/deploy.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: nginx-ingress
spec:
rules:
- host: nginx.example.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: nginx
port:
number: 80
http://nginx.example.com
✅ 防火墙
firewall-cmd --add-port=30000-32767/tcp --permanent
firewall-cmd --reload
✅ SELinux(必要时)
setenforce 0
✅ 网络插件
| 场景 | 推荐 |
|---|---|
| 测试 | NodePort |
| 裸机生产 | MetalLB + LoadBalancer |
| 多服务 | Ingress |
如果你愿意,可以告诉我:
我可以给你精确命令方案。