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

Docker容器中Chrome for Testing无法启动的问题求助

Docker容器中运行Chrome for Testing的问题修复方案

问题背景

在Docker容器中配置Chrome for Testing与ChromeDriver后,运行Java自动化代码时出现SessionNotCreatedException,核心报错为Driver server process died prematurely,导致无法创建浏览器会话。

原配置与代码

Dockerfile

RUN microdnf install -y unzip
ARG CHROME_VERSION=116.0.5845.96
RUN curl -s -o  /tmp/chrome-linux64.zip https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$CHROME_VERSION/linux64/chrome-linux64.zip \
    && unzip /tmp/chrome-linux64.zip -d /opt \
    && ln -s /opt/chrome-linux64/chrome /usr/local/bin/chrome \
    && rm /tmp/chrome-linux64.zip

## ChromeDriver

ARG CHROME_DRIVER_VERSION=116.0.5845.96
RUN curl -s -o /tmp/chromedriver_linux64.zip https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$CHROME_DRIVER_VERSION/linux64/chromedriver-linux64.zip \
    && unzip /tmp/chromedriver_linux64.zip -d /opt/selenium \
    && rm /tmp/chromedriver_linux64.zip \
    && mv /opt/selenium/chromedriver-linux64/chromedriver /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION  \
    && chmod 755 /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION \
    && ln -s /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION /usr/bin/chromedriver

ENV CHROMEDRIVER_PORT 4444
ENV CHROMEDRIVER_WHITELISTED_IPS "127.0.0.1"
ENV CHROMEDRIVER_URL_BASE ''
EXPOSE 4444

EXPOSE 8080
EXPOSE 5005
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
# For Testing
ENTRYPOINT ["java","-jar", "-Xmx600m","/app.jar"]

Java代码

ChromeDriverService service = new ChromeDriverService.Builder()
                .withVerbose(false)
                .withSilent(true)
                .build();
        try {
            java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.WARNING);
//            service.sendOutputTo(new FileOutputStream("/dev/null"));
            service.sendOutputTo(OutputStream.nullOutputStream());
        } catch (Exception e) {
            LOGGER.error("Unable to suppress output");
        }
        return new ChromeDriver(service, getChromeOptions(useFastStrategy));

private ChromeOptions getChromeOptions(boolean useFastStrategy) {
        ChromeOptions chromeOptions = new ChromeOptions();


        chromeOptions.addArguments(String.format("user-agent=%s", USER_AGENT));
        chromeOptions.addArguments("--log-level=OFF");
        chromeOptions.addArguments("--headless=new");
        List<String> arguments = new LinkedList<>();
        arguments.add("--disable-extensions");
        // disable-infobars no longer works, see the following link for a potential answer:
        // https://stackoverflow.com/questions/57298901/unable-to-hide-chrome-is-being-controlled-by-automated-software-infobar-within
        // also see
        // https://qaautomation.expert/2022/04/01/how-to-disable-infobar-warning-for-chrome-tests-in-selenium/ . Perhaps
        // comment out 'arguments.add("disable-infobars");' in the future or try
        // chromeOptions.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation")); // <- maybe try this
        // instead of 'arguments.add("disable-infobars");'
        arguments.add("disable-infobars"); // try enabling this to try and save some cpu
        arguments.add("--headless");
        arguments.add("--disable-gpu");
        arguments.add("--no-sandbox");
        arguments.add("--incognito");
        arguments.add("--disable-application-cache");
        arguments.add("--disable-dev-shm-usage");

        chromeOptions.addArguments(arguments);
        return chromeOptions;
    }

报错信息

org.openqa.selenium.SessionNotCreatedException: Could not start a new session. Possible causes are invalid address of the remote server or browser start-up failure. 
Host info: host: '22e9e505804a', ip: '172.17.0.2'
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:536)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:232)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:159)
    at org.openqa.selenium.chromium.ChromiumDriver.<init>(ChromiumDriver.java:108)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:88)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:83)
...
Caused by: org.openqa.selenium.WebDriverException: Driver server process died prematurely.
Build info: version: '4.11.0', revision: '040bc5406b'
System info: os.name: 'Linux', os.arch: 'amd64', os.version: '5.15.49-linuxkit', java.version: '17.0.2'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:237)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:119)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:518)
...

修复方案

1. 完善Dockerfile:补充依赖与权限设置

Alpine镜像缺少Chrome运行必需的系统库,且root用户运行Chrome会触发安全限制,需修改Dockerfile如下:

FROM openjdk:17-alpine

# 安装Chrome运行依赖:系统库、字体(避免渲染异常)
RUN microdnf install -y unzip glibc nss freetype fontconfig

# 创建非root用户,规避Chrome的root运行限制
RUN addgroup -S chrome && adduser -S chrome -G chrome

ARG CHROME_VERSION=116.0.5845.96
RUN curl -s -o /tmp/chrome-linux64.zip https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$CHROME_VERSION/linux64/chrome-linux64.zip \
    && unzip /tmp/chrome-linux64.zip -d /opt \
    && ln -s /opt/chrome-linux64/chrome /usr/local/bin/chrome \
    && rm /tmp/chrome-linux64.zip \
    && chown -R chrome:chrome /opt/chrome-linux64

ARG CHROME_DRIVER_VERSION=116.0.5845.96
RUN curl -s -o /tmp/chromedriver_linux64.zip https://edgedl.me.gvt1.com/edgedl/chrome/chrome-for-testing/$CHROME_DRIVER_VERSION/linux64/chromedriver-linux64.zip \
    && unzip /tmp/chromedriver_linux64.zip -d /opt/selenium \
    && rm /tmp/chromedriver_linux64.zip \
    && mv /opt/selenium/chromedriver-linux64/chromedriver /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION  \
    && chmod 755 /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION \
    && ln -s /opt/selenium/chromedriver-$CHROME_DRIVER_VERSION /usr/bin/chromedriver \
    && chown -R chrome:chrome /opt/selenium

# 切换到非root用户运行
USER chrome

ENV CHROMEDRIVER_PORT 4444
ENV CHROMEDRIVER_WHITELISTED_IPS "127.0.0.1"
ENV CHROMEDRIVER_URL_BASE ''
EXPOSE 4444

EXPOSE 8080
EXPOSE 5005
ARG JAR_FILE=target/*.jar
COPY ${JAR_FILE} app.jar
ENTRYPOINT ["java","-jar", "-Xmx600m","/app.jar"]

2. 优化Java代码:修复参数冲突与路径指定

原代码存在headless参数冲突、失效参数未替换等问题,修改后如下:

ChromeDriverService service = new ChromeDriverService.Builder()
        .withVerbose(false)
        .withSilent(true)
        // 明确指定ChromeDriver路径,避免自动查找失败
        .usingDriverExecutable(new File("/usr/bin/chromedriver"))
        .build();
try {
    java.util.logging.Logger.getLogger("org.openqa.selenium").setLevel(Level.WARNING);
    service.sendOutputTo(OutputStream.nullOutputStream());
} catch (Exception e) {
    LOGGER.error("Unable to suppress output");
}
return new ChromeDriver(service, getChromeOptions(useFastStrategy));

private ChromeOptions getChromeOptions(boolean useFastStrategy) {
    ChromeOptions chromeOptions = new ChromeOptions();

    // 指定Chrome二进制文件路径
    chromeOptions.setBinary("/usr/local/bin/chrome");

    chromeOptions.addArguments(String.format("user-agent=%s", USER_AGENT));
    chromeOptions.addArguments("--log-level=OFF");
    // 仅保留新的headless模式,删除重复的旧参数
    chromeOptions.addArguments("--headless=new");
    
    List<String> arguments = new LinkedList<>();
    arguments.add("--disable-extensions");
    // 替换失效的disable-infobars,隐藏自动化提示
    chromeOptions.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));
    arguments.add("--disable-gpu");
    arguments.add("--no-sandbox");
    arguments.add("--incognito");
    arguments.add("--disable-application-cache");
    arguments.add("--disable-dev-shm-usage");
    // 添加窗口大小参数,避免headless模式布局异常
    arguments.add("--window-size=1920,1080");
    
    // 可选:启用快速策略时禁用图片加载
    if (useFastStrategy) {
        chromeOptions.addArguments("--blink-settings=imagesEnabled=false");
    }

    chromeOptions.addArguments(arguments);
    return chromeOptions;
}

3. 核心问题总结

  • 依赖缺失:Alpine镜像默认缺少Chrome运行所需的glibc、nss等系统库,导致浏览器启动失败。
  • 权限限制:Chrome默认禁止root用户运行,即使添加--no-sandbox仍可能触发异常,需切换非root用户。
  • 参数冲突:同时使用--headless=new和--headless会导致Chrome启动逻辑混乱,需保留新版headless参数。
  • 路径模糊:未明确指定Chrome与ChromeDriver的二进制路径,可能导致Driver无法定位到浏览器。

内容的提问来源于stack exchange,提问作者HeronAlgoSearch

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:42:31