在 Gitlab Shared Runner 中运行 docker 容器

问题描述 投票:0回答:1

我正在尝试在 .gitlab-ci.yml 文件中运行带有 mongo 映像的 docker 容器。我的一些 python 文件与 mongo 数据库通信。这是我的 .gitlab-ci.yml 的样子:

default:
  image: python:3.10

variables:
  DOCKER_HOST: "tcp://docker:2375"
  DOCKER_DRIVER: overlay2
  DOCKER_TLS_CERTDIR: ""

services:
  - docker:dind

test-job:
  stage: test
  script:
    # install virtualenv (installs into /usr/local/bin)
    - pip3 install virtualenv
    # create virtual env
    - virtualenv venv
    # activate it
    - source venv/bin/activate
    # install necessary packages into virtual env
    - pip3 install -r requirements.txt

    # Need to download docker, otherwise get a docker: command not found error
    - apt-get update && apt-get install -y docker.io

    # Run the mongo container
    - docker run -d --name mongo-container mongo:latest
    - python -m pytest tests/

但是,我得到了

docker: error during connect: Post "http://docker:2375/v1.24/containers/create?name=mongo_": dial tcp 198.82.184.81:2375: connect: no route to host.

有人对去哪里有什么建议吗? 谢谢你

docker gitlab gitlab-ci-runner docker-in-docker
1个回答
0
投票

考虑将 mongo 数据库实例化为 gitlab 服务,而不是使用

docker:dind
。这将为您与主容器并行创建 mongo 容器,然后主容器可以与 mongo 容器交互。

.gitlab-ci.yml:

stages:
  - test

variables:
  MONGO_INITDB_ROOT_USERNAME: "admin"
  MONGO_INITDB_ROOT_PASSWORD: "password"

services:
  - name: mongo:4
    alias: mongodb

test:
  stage: test
  image: python:3.11
  before_script:
    - python -m ensurepip
    - pip install pymongo
  script:
    - python example.py

示例.py

from pymongo import MongoClient

# Connect to host "mongodb" (alias of the gitlab service) at default port (27017)
client = MongoClient("mongodb", 27017)

# Interact with the DB
db = client["my_database"]
collection = db["my_collection"]
© www.soinside.com 2019 - 2024. All rights reserved.