简体   繁体   English

如何将gitlab中的golang连接到gitlab-ci中的mongodb容器

[英]how to connect golang in gitlab to mongodb container in gitlab-ci

I want to connect my golang code (without a container) to the monogdb container, when it is local it works.我想将我的 golang 代码(没有容器)连接到 monogdb 容器,当它在本地时它可以工作。

when I push it to gitlab.ci using container, connection refused当我使用容器将其推送到 gitlab.ci 时,连接被拒绝

previously I used to use testing in dockerfile, but I don't use that.以前我曾经在dockerfile中使用测试,但我不使用它。

the code is like this代码是这样的

image: docker:latest
services:
  - docker:dind

stages:
  - test

variables:
  REPO_NAME: $REPO_URL
  DOCKER_HOST: tcp://docker:2375
  DOCKER_DRIVER: overlay2


test:
  stage: test
  before_script:
    - apk add go make bash docker-compose
    # - make service-up-test
  script:
    - make mongodb-test-up
    - go clean -testcache && go test -v ./app/test

and golang test:和 golang 测试:

package codetify

import (
    "context"
    "log"
    "testing"

    "github.com/stretchr/testify/assert"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
    "go.mongodb.org/mongo-driver/mongo/readpref"
)

var credential = options.Credential{
    Username: "usernametest",
    Password: "passwordtest",
}
var addr = "mongodb://0.0.0.0:27018"

func InitMongoDB() *mongo.Database {
    clientOpts := options.Client().ApplyURI(addr).SetAuth(credential)
    clientOpts.SetDirect(true)
    client, err := mongo.Connect(context.TODO(), clientOpts)
    if err != nil {
        log.Println("client", client)
        return nil
    }
    return client.Database("databasetest")
}

func TestPingMongoDBServer(t *testing.T) {
    clientOpts := options.Client().ApplyURI(addr).SetAuth(credential)
    clientOpts.SetDirect(true)
    client, err := mongo.Connect(context.TODO(), clientOpts)
    assert.Equal(t, err, nil, "Shoudl be not error")
    err = client.Ping(context.Background(), readpref.Primary())
    assert.Equal(t, err, nil, "Shoudl be not error")
}

[Next] [下一个]

this is a docker-compose.yml for mongodb, for testing, i use another port这是 docker-compose.yml 用于 mongodb,为了测试,我使用另一个端口

version: '3'
services: 
    database:
        image:  'mongo:latest'
        container_name: '${APP_NAME}-mongodb-test'
        environment: 
            MONGO_INITDB_ROOT_USERNAME: usernametest
            MONGO_INITDB_ROOT_PASSWORD: passwordtest
            MONGO_INITDB_DATABASE: databasetest
        command: mongod
        ports:
            - '27018:27017'
        restart: always
        volumes: 
            - ./resources/mongo-initdb.js:/docker-entrypoint-initdb.d/mongo-initdb.js
        networks: 
            - codetify-net-test
networks: 
    codetify-net-test

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM