7

Kubernetes 配置Pod使用代理上网

 8 months ago
source link: https://blog.51cto.com/saynaihe/9101344
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

配置Kubernetes Pod使用代理上网

在企业网络环境中进行Kubernetes集群的管理时,经常会遇到需要配置Pods通过HTTP代理服务器访问Internet的情况。这可能是由于各种原因,如安全策略限制、网络架构要求或者访问特定资源的需要。本文将介绍配置Kubernetes中Pod使用代理的两种常见方式:通过ConfigMap和直接在应用程序环境变量中设置。

Kubernetes集群中配置Pod使用代理的场景可能包括:

  1. 执行出站流量控制和审计。
  2. 遵守网络访问策略,强制流量通过指定的出口点。
  3. 实现服务的代理隔离,以加强内网安全。
  4. 访问外部应用,我的场景是调用 discord api。

接下来将介绍两种常用配置方法:

配置方式一:使用ConfigMap

步骤1:创建ConfigMap

创建一个名为proxy-config的ConfigMap以包含代理设置信息:

apiVersion: v1
kind: ConfigMap
metadata:
  name: proxy-config
data:
  http_proxy: http://<proxy-server>:<port>
  https_proxy: http://<proxy-server>:<port>
  no_proxy: .cluster.local,.svc,.my-company.com,127.0.0.1

替换<proxy-server><port>为实际代理服务器的地址和端口。

步骤2:在Pod定义中引用ConfigMap

修改Pod的定义以使用ConfigMap中的环境变量:

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
    - name: example-container
      image: nginx
      envFrom:
        - configMapRef:
            name: proxy-config
步骤3:确认应用程序能正确使用代理

在Pod应用程序中,确保这些环境变量能被正确地使用。比如,在诸如curl、wget这样的命令行工具中,HTTP_PROXY和HTTPS_PROXY环境变量是自动识别的,而一些编程语言的HTTP客户端库可能需要在代码中显式配置代理。

配置方式二:直接在部署的环境变量中设置

步骤1:在Pod定义中设置环境变量

与ConfigMap不同,可以直接在Pod或者Deployment的定义中设置环境变量,我这里是直接使用了环境变量的方式:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: example-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: example
  template:
    metadata:
      labels:
        app: example
    spec:
      containers:
      - name: example-container
        image: nginx
        env:
        - name: http_proxy
          value: http://<proxy-server>:<port>
        - name: https_proxy
          value: http://<proxy-server>:<port>
        - name: no_proxy
          value: .cluster.local,.svc,.my-company.com,127.0.0.1

这种方法允许更灵活的设置,因为你可以为不同的Deployment指定不同的代理设置。

步骤2:应用更改并确认应用程序的代理配置

同样的,确保你的应用程序或服务读取并正确使用了这些环境变量设置。

  • http_proxy / https_proxy: 指定HTTP/HTTPS的代理服务器,格式为http://<proxy-user>:<proxy-password>@<proxy-server>:<port>
  • no_proxy: 指定的地址不通过代理服务器访问。通常包括Kubernetes的服务发现后缀如.cluster.local.svc以及本地网络的范围。

测试代理设置

部署Pod后,我们可以测试这些设置是否生效:

  1. 进入Pod的shell环境:
kubectl exec -it example-pod -- /bin/sh
  1. 使用curl测试代理是否工作:
 curl -I 'https://discord.com'
Kubernetes 配置Pod使用代理上网_proxy

如果返回了正常的HTTP响应,表明代理设置生效并正确工作。如果出现连接超时或代理错误,可能需要检查代理服务器配置和网络策略设置。
测试一下小伙伴给的discord的接口:

 curl --location --request POST 'https://discord.com/api/v10/oauth2/token'
Kubernetes 配置Pod使用代理上网_kubernetes_02

正确配置Kubernetes中的Pod使用HTTP代理是满足企业网络要求的关键环节。通过使用ConfigMap或直接在环境变量中设置代理信息,可以为集群的出站流量提供控制和灵活性。不过,记得在部署之前详细测试以确保一切按预期工作。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK