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

GitLab CI Docker登录失败:extra_hosts未生效致DNS解析错误

问题

使用单节点GitLab Runner运行CI/CD流水线,已在gitlab-ci.yml及Runner的config.toml中配置extra_hosts,流水线输出确认hosts条目已正确设置,但执行docker login步骤时出现错误:Docker未使用配置的hosts,而是通过外部DNS服务器解析registry.gitlab.example.com,提示找不到主机。

相关配置

gitlab-ci.yml

stages:
  - build

default:
  tags:
    - shared

variables:
  DOCKER_IMAGE: "$CI_REGISTRY_IMAGE:$CI_COMMIT_REF_SLUG"

build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  script:
    - cat /etc/hosts
    - ping -c 4 10.10.30.2    
    - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY
    - docker build -t $DOCKER_IMAGE .
    - docker push $DOCKER_IMAGE
  only:
    - branches

Runner的config.toml

extra_hosts = ["gitlab.example.com:10.10.30.2", "registry.gitlab.example.com:10.10.30.2"]

流水线输出与报错

确认hosts条目正确:

10.10.30.2 gitlab.example.com
10.10.30.2 registry.gitlab.example.com

报错信息:

Error response from daemon: Get "https://registry.gitlab.example.com/v2/": dial tcp: lookup registry.gitlab.example.com on 193.110.81.0:53: no such host
解决方案

问题核心是:你配置的extra_hosts只作用于主作业容器(即docker:latest容器),但docker login调用的是docker:dind服务容器内的Docker daemon,这个服务容器并未继承主容器的hosts配置,因此会使用自身的DNS解析。

解决方法如下:

1. 给docker:dind服务单独配置extra_hosts

在gitlab-ci.yml的services字段中,直接为docker:dind添加extra_hosts配置,确保dind容器的hosts被正确设置:

build:
  stage: build
  image: docker:latest
  services:
    - name: docker:dind
      extra_hosts:
        - "gitlab.example.com:10.10.30.2"
        - "registry.gitlab.example.com:10.10.30.2"
  # 其余配置保持不变

2. 通过环境变量传递hosts配置到dind容器

利用DOCKER_OPTS环境变量,将hosts映射参数传递给dind容器内的Docker daemon,启动时自动生效:

build:
  stage: build
  image: docker:latest
  services:
    - docker:dind
  variables:
    DOCKER_HOST: tcp://docker:2376
    DOCKER_OPTS: "--add-host gitlab.example.com:10.10.30.2 --add-host registry.gitlab.example.com:10.10.30.2"
  # 其余配置保持不变

3. 修改Runner全局配置(所有流水线生效)

如果需要让该Runner执行的所有流水线都生效,可以修改config.toml,通过services_extra_hosts字段为服务容器统一配置hosts,修改后需重启Runner服务:

[[runners]]
  name = "shared-runner"
  url = "https://gitlab.example.com/"
  token = "your-runner-token"
  executor = "docker"
  extra_hosts = ["gitlab.example.com:10.10.30.2", "registry.gitlab.example.com:10.10.30.2"]
  [runners.docker]
    tls_verify = false
    image = "docker:latest"
    privileged = true
    services_extra_hosts = ["gitlab.example.com:10.10.30.2", "registry.gitlab.example.com:10.10.30.2"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 22:39:58