我有一个包含3个容器A,B和C的容器。我想从C访问容器A和B中的服务。localhost:<port>
不起作用,127.0.0.1
也不起作用。
我的yaml
apiVersion: "v1"
kind: Pod
metadata:
name: web3
labels:
name: web
app: demo
spec:
containers:
- name: client
image: ubuntu
command: ['cat']
tty: true
- name: apache1
image: nimmis/apache-php5
ports:
- containerPort: 8080
name: apacheport1
protocol: TCP
- name: apache2
image: nimmis/apache-php5
command: ['cat']
tty: true
ports:
- containerPort: 8088
name: apacheport2
protocol: TCP
我在做什么
kubectl apply -f example.yaml
kubectl exec -it web3 -c client bash
然后尝试到达其他2个服务
root@web3:/# curl http://localhost:8080
curl: (7) Failed to connect to localhost port 8080: Connection refused
root@web3:/# curl http://localhost:8088
curl: (7) Failed to connect to localhost port 8088: Connection refused
root@web3:/# curl http://localhost:80
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!--
Modified from the Debian original for Ubuntu
问题
如何使前两个 curl 工作。 (我不想使用该服务,因为我的用例仅用于测试目的)
当我没有暴露端口时为什么要打开80端口。
最佳答案
关键是Apache使用nimmis/apache-php5
监听端口80。
因此,暴露的是端口80。
通过containerPort: <P>
,您并不是要将容器的端口80暴露给<P>
,而是要暴露端口<P>
本身。另外,如文档Not specifying a port here DOES NOT prevent that port from being exposed.
所示。
我没有找到将内部容器端口映射到Pod中其他端口的方法。但是,您可以通过字段hostPort
将内部容器端口映射到主机端口。
apiVersion: "v1"
kind: Pod
metadata:
name: web3
labels:
name: web
app: demo
spec:
containers:
- name: client
image: ubuntu
command: ['cat']
tty: true
- name: apache1
image: nimmis/apache-php5
ports:
- containerPort: 80
name: apacheport1
hostPort: 8002
protocol: TCP
- name: apache2
image: nimmis/apache-php5
command: ['cat']
tty: true
ports:
- containerPort: 80
hostPort: 8001
name: apacheport2
protocol: TCP
然后在Minikube上获得节点的IP
$ minikube ip # e.g., 192.168.97.100
并从
client
检查是否可以访问Apache服务:$ kubectl exec -it web3 -c client bash
# apt-get update && apt-get install curl
# curl 192.168.99.100:8002
关于kubernetes - Kubernetes多容器Pod中的容器间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55065273/