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

时间:2020-10-25 10:10:41

标签: mongodb go gitlab gitlab-ci

我想将golang代码(无容器)连接到monogdb容器,当它在本地时可以工作。

当我使用容器将其推送到gitlab.ci时,连接被拒绝

以前我曾经在dockerfile中使用测试,但是我不使用它。

代码是这样的

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

和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")
}

1 个答案:

答案 0 :(得分:0)

[下一步]

这是用于mongodb的docker-compose.yml,用于测试,我使用另一个端口

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