首页 > 解决方案 > GITLAB-CI - 加入由 docker-compose 创建的网络

问题描述

我正在创建一个 gitlab-ci 来在我的应用程序上运行 e2e 测试,所以,假设我有这个 docker-compose.yml:

services:
  chrome:
    image: zenika/alpine-chrome:latest
    command: [
      chromium-browser,
      "--headless",
      "--no-sandbox",
      "--disable-gpu",
      "--ignore-certificate-errors",
      "--reduce-security-for-testing",
      "--remote-debugging-address=0.0.0.0",
      "--remote-debugging-port=9222",
      "https://google.com/",
    ]
    ports:
      - "9222:9222"
    networks:
      - test-e2e

networks:
  test-e2e:
    ipam:
      driver: default
      config:
        - subnet: 172.28.0.0/16

当我运行docker-compose up一切正常时,在我的本地机器上我可以访问localhost:9222和访问 chrome 调试器。


但是,当我在 gitlab-ci 上运行相同的作业时,我得到一个 ECONNREFUSED 错误

F---F

Failures:

1) Scenario: List of Profiles # src/features/profile.feature:3
   ✖ Before # dist/node/development/webpack:/hooks/puppeteer.hooks.ts:17
       Failed to fetch browser webSocket url from http://localhost:9222/json/version: connect ECONNREFUSED 127.0.0.1:9222
       Error: connect ECONNREFUSED 127.0.0.1:9222
           at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1191:14)

所以很明显我无法加入 docker-compose 网络并localhost:9222从工作中访问

gitlab-ci.yml的很简单,看起来像这样:

E2E tests:
  stage: test end-to-end
  image:
    name: docker/compose:1.24.1
    entrypoint: ["/bin/sh", "-c"]
  services:
    - docker:dind
  before_script:
    - apk --update add nodejs yarn
    - docker-compose -f test-e2e.yaml up -d
  script:
    - yarn test:cucumber
  after_script:
    - docker-compose -f test-e2e.yaml down

yarn test:cucumber基本上运行 cucumber 和 puppeteer 试图访问localhost:9222以获取 chrome 的元数据。


如何从 gitlab-ci 作业加入 docker-compose 创建的网络?

标签: dockerdocker-composegitlabdockerfilegitlab-ci

解决方案


TL; DR在 CI 上,您的chrome容器可以使用docker:9222(或更一般地<name-of-the-dind-service-on-ci>:<exposed-port>)访问,而不是localhost:9222

解释

根据您的gitlab-ci.yml,您将启动 2 个容器:

在 Docker 中运行容器时,容器实际上是由 Docker 守护进程启动的,并将在运行守护进程的主机上运行并公开端口。

  • 在您的机器上,Docker 守护程序在本地运行,并将公开本地网络上的容器端口,允许您chrome通过以下方式访问您的容器localhost
  • 在 CI 上,您正在从docker/compose:1.24.1容器运行命令,但 Docker 守护程序正在另一个容器(不同的主机)中运行:docker:dind容器。chrome容器将在容器内创建,docker:dind并且它的端口从同一个容器中暴露出来。您只需要访问docker:dind将公开chrome端口的容器。

通过localhost从您的docker/compose:1.24.1容器中使用,您将无法访问chrome,因为它的端口未暴露在docker/compose:1.24.1容器上,而是从docker:dind容器中暴露。您需要指定它的主机 ( docker) 和暴露的端口 ( 9222)


推荐阅读