docker - 我的管道不允许我通过 golang 连接,尽管它可以在开发环境中工作

标签 docker go environment-variables gitlab

我有一个 .gitlab-ci.yml 文件,稍后将 golang 图像和 MySql 图像用作服务...

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

我在我的 go 应用程序中也有一个测试,它在我的开发机器上运行良好,正如你将在上面看到的,我在 gitlab-ci.yml 文件中设置了环境变量(这与我的开发环境相匹配。

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

但是当我运行我的管道时,我收到以下错误...

$ 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

是否需要更改gitlab-ci.yml文件中的环境变量?

最佳答案

正如 Seddik 已经指出的那样,localhost 不是 MySQL 服务器将监听的主机;它将以 mysql 的名称提供。

此外,命令 env="root:rootroot@tcp(localhost:3306)/TESTDB" 在 shell 中设置一个局部变量。它不影响环境变量。

设置环境变量

  • 导出局部变量
  • 或者使用变量字典
  • 或者专门为 go test 命令设置变量:
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 ./...


关于docker - 我的管道不允许我通过 golang 连接,尽管它可以在开发环境中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56793930/

相关文章:

docker - 无法在 Docker 容器中获取 ASPNETCORE_ENVIRONMENT 变量

go - Docker-Compose:与需要相对导入的 Dockerfiles 组合

mysql - 与在 docker 中运行的 mysql 连接缓慢

java - 云配置收到请求执行错误。端点=默认端点{ serviceUrl='http ://localhost:8761/} from Eureka server

regex - 无法在正则表达式中捕获单引号

json - 在 Go 中维护未解析的 JSON 字段的最佳方法是什么?

amazon-web-services - 如何在Gitlab CI/CD中启动Docker容器

go - 无法读取 RSA key

c - 什么是 LD_PRELOAD 技巧?

r - 以编程方式设置环境变量