knativeport, gunicorn port,k8s port的联系

1、Gunicorn启动server时如何选定端口?

 

 

 

如图这是一个用flask定义的简单的web server,我们平时在本地开发时,一般会受用flask自带的server启动app,那么其会采用__main__中定义的port、host来启动。

但是因为自带的server性能不好,在上线时一般会选择gunicorn等server。Gunicorn在用上面这个文件时,会采用import的方式,找到app,然后启动,所以文件中__main__中的语句都不会执行,那么__main__中的port和host也就不会被gunicorn采用。

Gunicorn 在启动app时,一般通过gunicorn –bind :$PORT –workers 1 – threads 8 app:app的命令来启动,当环境变量PORT定义了时,Gunicorn是通过-b :$PORT的方式绑定端口,如果PORT没有定义的话,默认使用127.0.0.1:8000。如果我们在容器中启动server,那么要注意gunicorn使用的端口号,要和容器暴露的端口号一致。

 

2、Kfserving创建服务时是如何传递端口信息给启动容器的Gunicorn的?

 

我们在用kfserving创建InferenceService时,是如何给容器传递port信息的呢?

答案是kfserving会在pod的定义中,根据containerPort的值,给pod加入一个“PORT: 端口值”的环境变量。

这样,pod中的容器在启动时,就能利用PORT这个环境变量,采用—bind :$PORT的方式启动web serer了。

 

 

注意,即使在不给containerPort时,knative会自动加入一个PORT为8080的环境变量,PORT是knative的一个保留的环境变量,不仅用于容器的端口号,也用于knative进行probe。用的是tcpSocket类型的探针。

 

3、K8s servie的port、targetPort、nodePort和Gunicorn、containerPort的关系?

 

 

 

 

 

如果我们不用kfserving创建的InferenceService,而只想用k8s的原生的Service创建服务呢?

那我们就要先创建一个Deployment,再创建一个Service,通过Service暴露服务给用户。

这样就需要搞明白Service的port、targetPort、nodePort和pod的containerPort以及gunicorn使用的PORT之间用什么关系了。

先看一个Deployment的例子:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 8081
        env:
          -name: PORT
           value: “8081”

 

这个Deployment会启动三个Pod,要想访问每个pod内的应用容器,都需要通过8081端口,即这个8081端口在containerPort这儿定义。如果我们使用gunicorn启动server,那么需要在env中定义一个PORT,并将8081传入。

然后再创建一个nodePort类型的Service:

apiVersion: v1
kind: Service
metadata:
  name: my-service
spec:
  type: NodePort
  selector:
    app: nginx
  ports:
      # By default and for convenience, the `targetPort` is set to the same value as the `port` field.
    - port: 80
      targetPort: 8081
      # Optional field
      # By default and for convenience, the Kubernetes control plane will allocate a port from a range (default: 30000-32767)
      nodePort: 30007

port用于集群内部通信,集群内部的pod访问service时,可通过clusterip:port来访问service。

nodePort是给集群外部用户方位集群内部service提供的端口,外部用户可通过nodeIp:nodePort来访问service。

targetPort是pod内容器对应端口,这个需要和containerPort配置一致才行。从nodePort过来的流量,会经过kube-proxy流入后端的pod的targetPort上。

 

 

参考:

https://blog.csdn.net/yjk13703623757/article/details/79819415

https://docs.gunicorn.org/en/stable/settings.html

posted on 2021-11-26 11:17  MissSimple  阅读(234)  评论(0编辑  收藏  举报

导航