在GitLab CI管道中,我需要将自己的C ++代码从Docker容器连接到以servive身份运行的MongoDB,但我无法连接。
这是一个显示问题的最小gitlab-ci.yml示例:
stages:
- connect1
- connect2
image: docker:latest
variables:
MONGOIMAGE: "mongo:4.2.3-bionic"
MONGO_INITDB_ROOT_USERNAME: "root"
MONGO_INITDB_ROOT_PASSWORD: "geheim"
connect1:
stage: connect1
services:
- name: $MONGOIMAGE
image: mongo
script:
- mongo --host mongo --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --eval "db.help()"
connect2:
stage: connect2
services:
- name: $MONGOIMAGE
script:
- docker run --rm mongo mongo --host mongo --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --eval "db.help()"
connect2的错误消息是找不到主机:
connecting to: mongodb://mongo:27017/?compressors=disabled&gssapiServiceName=mongodb
2020-06-04T16:20:47.614+0000 E QUERY [js] Error: couldn't connect to server mongo:27017, connection attempt failed: HostNotFound: Could not find address for mongo:27017: SocketException: Host not found (authoritative) :
connect@src/mongo/shell/mongo.js:341:17
@(connect):2:6
2020-06-04T16:20:47.615+0000 F - [main] exception: connect failed
2020-06-04T16:20:47.615+0000 E - [main] exiting with code 1
我已经尝试过使用--host localhost
,但是这样做的效果更好。如何实现以docker run
开头的容器(如connect2中)可以连接到MongoDB服务?
答案 0 :(得分:1)
最后我找到了解决方法:
connect2:
stage: connect2
services:
- name: $MONGOIMAGE
script:
- ping mongo -c 5
- docker run --rm mongo mongo --add-host mongo:`cat /etc/hosts | grep mongo | awk '{print $1}'` --net host --username $MONGO_INITDB_ROOT_USERNAME --password $MONGO_INITDB_ROOT_PASSWORD --eval "db.help()"
答案 1 :(得分:0)
Docker是客户端/服务器应用程序。您正在运行客户端,但是没有服务器。因此,您需要使用Docker-in-Docker运行Docker守护程序。
您可以在此处查看示例GitLab CI配置:https://stackoverflow.com/a/61106578/6214034
以及相关文档:https://docs.gitlab.com/ee/ci/docker/using_docker_build.html