You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kubernetes集群中应用容器连接Selenium Sidecar容器的正确URL配置问题

Kubernetes集群中应用容器连接Selenium Sidecar容器的正确URL配置问题

看起来你在Kubernetes里配置Selenium作为应用的sidecar容器时遇到了连接异常,我来帮你梳理问题点和正确的配置思路:

首先要指出你YAML配置里的一个核心问题:你把remote-chrome-webdriver这个Selenium容器放到了initContainers字段下,但init容器是用来完成一次性初始化任务的,执行完毕就会退出,而Selenium需要持续运行才能提供WebDriver服务——这直接导致你的应用容器启动后,Selenium容器已经不在运行状态,自然会抛出ConnectException。

第一步:修正YAML的容器结构

你需要把remote-chrome-webdriver容器从initContainers移到Pod的containers字段下,和你的应用容器平级,这样它会和应用容器一起持续运行。调整后的YAML大致结构如下:

apiVersion: v1
kind: Pod
metadata:
  name: your-app-pod
spec:
  initContainers:
    - name: wait-for-chrome
      image: busybox:latest
      imagePullPolicy: IfNotPresent
      # 这里改成localhost,因为同Pod共享网络
      command: ['sh', '-c', 'until curl -f http://localhost:4444/wd/hub/status; do echo "Waiting for remote-chrome-webdriver..."; sleep 5; done;']
      resources: {{- toYaml .Values.resources | nindent 12 }}
  containers:
    - name: your-app-container
      # 这里填写你的应用容器镜像、端口等配置
    - name: remote-chrome-webdriver
      image: xxxxxxxxxx/selenium/standalone-chrome:4.23.1
      imagePullPolicy: IfNotPresent
      ports:
        - name: http
          containerPort: 4444
          protocol: TCP
      env:
        - name: "xxxxx_APPLICATION_CREDENTIALS"
          value: {{ .Values.env.xxxxxxxxxxx}}
      envFrom:
        - secretRef:
            name: xxxxxx
      volumeMounts:
        - name: xxxxxx
          readOnly: true
          mountPath: "/etc/xxxxx"
      resources: {{- toYaml .Values.resources | nindent 12}}
  restartPolicy: Always

第二步:Java代码里的正确URL

同一个Pod内的所有容器共享同一个网络命名空间,所以应用容器可以直接通过localhost访问sidecar容器的服务。你的Java代码应该使用这个URL:

URL remoteUrl = new URL("http://localhost:4444/wd/hub");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--no-sandbox", "--disable-dev-shm-usage");
log.info("starting web driver");
WebDriver driver = new RemoteWebDriver(remoteUrl, options);

为什么你之前的其他URL无效?

  • http://remote-chrome-webdriver.default.svc.cluster.local:4444/wd/hub:这是Kubernetes Service的集群域名,只有当你把Selenium容器暴露为独立Service时才会生效,但sidecar是和应用同Pod的,完全不需要走Service,而且如果没创建对应Service,这个域名根本无法解析。
  • http://remote-chrome-webdriver:4444/wd/hub:同Pod内的容器名确实可以作为主机名解析(K8s会自动添加hosts条目),但直接用localhost更简单可靠,两者效果一致,但localhost的可读性和通用性更强。

最后检查

你配置的ChromeOptions参数(--headless、--no-sandbox等)都是容器环境下运行Chrome的必要配置,这部分没问题。调整完上述内容后,应用容器应该就能正常连接到Selenium sidecar了。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.07 10:29:33