I am unable to reach a container on a port that I set in a deployment & service. I created a deployment with this command:
kubectl create deploy mydeploy --image nginx --replicas 2 --port 1234
And then, I created a service that should expose the pods of this deploy with:
kubectl expose deploy mydeploy --port 4444 --target-port 1234 --name my-svc
To test that my service is working, I create a temporary pod to curl the service:
kubectl run tmp-pod --image nginx:alpine -i --rm --restart Never -- curl <cluser-ip-of-service>:4444
but, this curl does not get the expected response. I decide to test the pod/container directly. The port 1234 does not work. But, if I curl one of the pods using port 80, it works:
kubectl run tmp --image nginx:alpine -i --rm --restart Never -- curl 192.168.1.18:80
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
...
Getting the configuration of one of the pods shows that the port was set correctly, yet port 80 is still being used:
apiVersion: v1
kind: Pod
metadata:
labels:
app: mydeploy
pod-template-hash: 86bd9fc56c
name: mydeploy-86bd9fc56c-shd9z
namespace: default
spec:
containers:
- image: nginx
imagePullPolicy: Always
name: nginx
ports:
- containerPort: 1234 # the port is set here, but still nginx is available on 80
protocol: TCP
Why is the port that I set for the deployment pods not working? Shouldn't the port I set be used as the targetPort
in the service? Am I misunderstanding how a pod's port and a service's port
and targetPort
work?
containerPort
tells kubernetes service where to route the traffic. The problem you're facing is that nothing is listening on the port you route the traffic to.
If you need to listen on 1234
, youy need to reconfigure the software in the container to bind to 1234. Frankly, this makes no sense, considering that your pods get dedicated networking namespaces, hence them listening on 80 is not in conflict with any other pod listening on 80 as well, you can have any number of pods binding to port 80 and they will not conflict/overlap.
Unless you have a very specific reason to change that default port,you should just leave it running as is, and target your service at containerPort 80.