我使用 Playwright v1.19.1 使用 .Net 6.0 创建了服务,并在 Ubuntu 20.04 上构建了一个镜像,如下所示:
- sdk:6.0-focal AS 构建
- 运行时:6.0-focal AS 运行时。
在我设置启动 Chromium 浏览器的代码中
await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions
{
Headless = false,
Channel = "chrome",
Args = new [] { "--disable-dev-shm-usage"}
});
下面是 Docker 文件:
FROM mcr.microsoft.com/dotnet/sdk:6.0-focal AS build
COPY . /app
WORKDIR /app
ENV PLAYWRIGHT_BROWSERS_PATH=/app/playwright
RUN dotnet restore "src/Service/Service.csproj"
RUN dotnet build "src/Service/Service.csproj" -c Release
RUN pwsh src/Service/bin/Release/net6.0/playwright.ps1 install chrome
RUN dotnet publish "src/Service/Service.csproj" -c Release -o /app/output
# =======================================================================================================
# Runtime
# =======================================================================================================
FROM mcr.microsoft.com/dotnet/runtime:6.0-focal AS runtime
EXPOSE 80
WORKDIR /home/site/wwwroot
COPY --from=build /app/output .
COPY --from=build /app/playwright .playwright/ms-playwright
ENV AzureWebJobsScriptRoot=/home/site/wwwroot \
AzureFunctionsJobHost__Logging__Console__IsEnabled=true \
PLAYWRIGHT_BROWSERS_PATH=/home/site/wwwroot/.playwright/ms-playwright
图像构建成功,但当我启动图像时出现以下错误。你知道如何解决这个问题吗?谢谢
Microsoft.Playwright.PlaywrightException: Browser closed.
==================== Browser output: ====================
<launching> /opt/google/chrome/chrome --disable-background-networking
--enable-features=NetworkService,NetworkServiceInProcess
--disable-background-timer-throttling --disable-backgrounding-occluded-windows
--disable-breakpad --disable-client-side-phishing-detection
--disable-component-extensions-with-background-pages
--disable-default-apps --disable-dev-shm-usage --disable-extensions
--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,
DestroyProfileOnBrowserClose,MediaRouter,AcceptCHFrame,AutoExpandDetailsElement
--allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection
--disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding
--disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run
--enable-automation --password-store=basic --use-mock-keychain
--no-service-autorun--export-tagged-pdf --no-sandbox --disable-dev-shm-usage
--user-data-dir=/tmp/playwright_chromiumdev_profile-HPOMeC
--remote-debugging-pipe --no-startup-window
<launched> pid=85
[pid=85][err] [85:85:0330/032427.114118:ERROR:ozone_platform_x11.cc(247)] Missing X server or $DISPLAY
[pid=85][err] [85:85:0330/032427.114193:ERROR:env.cc(225)] The platform failed to initialize. Exiting.
最佳答案
您需要在容器内设置 DISPLAY 环境参数 所以你需要在容器中执行以下操作:
export DISPLAY='{IP}:0'
同时使用“Headless = true”启动浏览器, 还添加 --disable-gpu 标志
如果您想使用 GUI 运行浏览器,请删除 GPU 标志并使用“Headless = false”启动浏览器
关于docker - 无法使用 .NET 在 Ubuntu Docker 镜像中启动 Playwright,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71671276/