我的管道不允许我通过golang连接,尽管它可以在开发环境中使用

I have a .gitlab-ci.yml file that uses the golang image and the MySql image later as a service...

gilab-ci.yml...

stages:
  - test
  - build
  - art

image: golang:1.9.2  



variables:
  BIN_NAME: alltools
  ARTIFACTS_DIR: artifacts
  GO_PROJECT: alltools
  GOPATH: /go


before_script:
  - mkdir -p ${GOPATH}/src/${GO_PROJECT}
  - mkdir -p ${CI_PROJECT_DIR}/${ARTIFACTS_DIR}
  - go get -u github.com/golang/dep/cmd/dep
  - go get -u github.com/fatih/color
  - go get -u github.com/go-sql-driver/mysql
  - cp -r ${CI_PROJECT_DIR}/* ${GOPATH}/src/${GO_PROJECT}/
  - cd ${GOPATH}/src/${GO_PROJECT}
  - env="root:rootroot@tcp(localhost:3306)/TESTDB"

test:
  stage: test
  services:
    - mysql:5.7
  variables:
    # Configure mysql environment variables (https://hub.docker.com/_/mysql/)
    # MYSQL_DATABASE: mydb
    MYSQL_ROOT_PASSWORD: rootroot

  script:
    # Run all tests         

    go test ./...


build:
  stage: build

  script:
    # Compile and name the binary as `hello`
    - go build -o alltools
    - pwd
    - ls -l alltools
    # Execute the binary
    - ./alltools
    # Move to gitlab build directory
    - mv ./alltools ${CI_PROJECT_DIR}
  artifacts:
    paths:
      - ./alltools

I also have a test in my go app which works fine on my dev machine, As you will see above I have set and enviroment varable in the gitlab-ci.yml file(this matches my dev enviroment.

  • env="root:rootroot@tcp(localhost:3306)/TESTDB"

But When i run my pipeline i get the following error...

$ env="root:rootroot@tcp(localhost:3306)/TESTDB" $ go test ./... ?
alltools [no test files] ? alltools/BBData [no test files] dial tcp 127.0.0.1:3306: getsockopt: connection refused

Do I need to change the environment variable in the gitlab-ci.yml file?

As Seddik pointed out already, localhost isn't the host that the MySQL server will be listening on; it will be available under the name mysql.

Additionally, the command env="root:rootroot@tcp(localhost:3306)/TESTDB" sets a local variable in the shell. It does not affect the environment variables.

To set an environment variable either

  • export the local variable
  • or use the variables dictionary
  • or set the variable specifically for the go test command:
variables:
  # Set your variable here for all jobs ...
  env: root:rootroot@tcp(mysql:3306)/TESTDB 

before_script:
  # ... or export it here ...
  - export env=root:rootroot@tcp(mysql:3306)/TESTDB

test:
  services:
    - mysql:5.7
  variables:
    # ... or set it here for this job only ...
    env: root:rootroot@tcp(mysql:3306)/TESTDB

  script:
    # ... or set it here for the go command only
    - env=root:rootroot@tcp(mysql:3306)/TESTDB go test ./...


You should use:

mysql

instead of:

localhost