Difference between targetPort and port in Kubernetes Service definition

前端 未结 7 1388
别跟我提以往
别跟我提以往 2020-12-02 04:56

A Kubernetes Service can have a targetPort and port in the service definition:

kind: Servi         


        
7条回答
  •  情话喂你
    2020-12-02 05:17

    The answer given above by @Manikanta P is correct. However, the explanation of "Port" might be a little unclear at first reading. I will explain with an example:

    Consider a Web-Application with its static content (front-page, images etc) hosted by httpd and the dynamic content (eg. response to requests, etc.) hosted by tomcat. The Webserver (or the static content) is served by httpd at port 80 while Appserver (or the dynamic content) is served by tomcat at port 8080.

    What a developer wants: User should be able to access the Webserver from outside BUT not the Appserver from outside.

    Solution: The service-type of Webserver in its service.yml will be NodePort while the service-type of Appserver in its service.yml will be ClusterIP.

    Code for webserver's service.yml:

    spec:
      selector:
        app: Webserver
      type: NodePort        // written to make this service accessible from outside.
      ports:
        - nodePort: 30475   // To access from outside, type :30475 in browser.
          port: 5050        // (ignore for now, I will explain below).
          protocol: TCP
          targetPort: 80  // port where httpd runs inside the webserver pod.
    

    Code for Appserver's service.yml

    spec:
      selector:
        app: appserver
      type: ClusterIP        // written to make this service NOT accessible from outside.
      ports:
        - port: 5050         // port to access this container internally
          protocol: TCP
          targetPort: 8080   // port where tomcat runs inside the appserver pod.
    

    Also Note, in the httpd.conf file of the Webserver, we will write the IP that redirects a user's request to the appserver. This IP will be: host_IP:5050.

    What exactly is happening here? A user writes hostIP:30475 and sees the Webserver's page. This is because it is being served by httpd at port 80 (targetport). When a user clicks a button, a request is made. This request is redirected to the Appserver because in httpd.conf file, the port 5050 is mentioned and this is the port where Appserver's container and Webserver's conatainer communicate internally. When the appserver receives the request, it is able to serve the request because of tomcat running inside it at port 8080.

提交回复
热议问题