douhuiyan2772 2016-03-15 03:31
浏览 250
已采纳

在docker容器中运行时,golang项目找不到依赖项

I have this golang sandbox project: https://github.com/cflynn07/golang-db-gateway-example

When I try to run gateway/gateway.go inside a golang:1.6.0-alpine

~/g/s/g/c/golang-db-gateway-example git:master ❯❯❯ docker-compose up gateway
mysql_server is up-to-date
Starting gateway
Attaching to gateway
gateway | gateway.go:7:2: cannot find package "github.com/go-sql-driver/mysql" in any of:
gateway |   /usr/local/go/src/github.com/go-sql-driver/mysql (from $GOROOT)
gateway |   /go/src/github.com/go-sql-driver/mysql (from $GOPATH)
gateway | gateway.go:8:2: cannot find package "github.com/gorilla/mux" in any of:
gateway |   /usr/local/go/src/github.com/gorilla/mux (from $GOROOT)
gateway |   /go/src/github.com/gorilla/mux (from $GOPATH)
gateway exited with code 1

Why isn't the build step detecting my project's dependencies inside the /example/vendor folder?

When I run go run gateway/gateway.go from my host OS, the command works.

Directory structure (mounted inside container at /example)

~/g/s/g/c/golang-db-gateway-example git:master ❯❯❯ tree -L 3
.
├── README.md
├── client
│   └── client.go
├── docker-compose.yml
├── gateway
│   └── gateway.go
├── glide.lock
├── glide.yaml
├── tmp
└── vendor
    └── github.com
        ├── go-sql-driver
        └── gorilla


Relevant files:

docker-compose.yml

mysql:
  container_name: mysql_server
  image: mysql:5.7.11
  environment:
    - MYSQL_ROOT_PASSWORD=root
  ports:
    - 3306
gateway:
  container_name: gateway
  image: golang:1.6.0-alpine
  volumes:
    - ./:/example
  working_dir: /example/gateway
  command: go run gateway.go
  environment:
    - MYSQL_ROOT_PASSWORD=root
    - MYSQL_DATABASE=sandbox
  links:
    - mysql

gateway/gateway.go

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gorilla/mux"
    "net/http"
    "os"
)

var db *sql.DB

func main() {
    r := mux.NewRouter()

    var e error
    db, e = sql.Open(
        "mysql", os.ExpandEnv("root:${MYSQL_SERVER_PASSWORD}@mysql_server:3306/${MYSQL_DATABASE}"))
    fmt.Print("error is", e)

    r.HandleFunc("/todos", getTodos).Methods("GET")

    http.ListenAndServe(":8080", r)
    fmt.Printf("gateway")
}

type todo struct{}

func getTodos(w http.ResponseWriter, r *http.Request) {
    t := new(todo)
    s, _ := json.Marshal(t)
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    fmt.Fprint(w, string(s))
}



Update 1 I changed my data-volume mount path inside the container to mount the project under the containers $GOPATH

mysql:
  container_name: mysql_server
  image: mysql:5.7.11
  environment:
    - MYSQL_ROOT_PASSWORD=root
  ports:
    - 3306
gateway:
  container_name: gateway
  image: golang:1.6.0-alpine
  volumes:
    - ./:/go/src/github.com/cflynn07/golang-db-gateway-example
  working_dir: /go/src/github.com/cflynn07/golang-db-gateway-example
  command: go run gateway/gateway.go
  environment:
    - MYSQL_ROOT_PASSWORD=root
    - MYSQL_DATABASE=sandbox
  links:
    - mysql

However now docker appears to hang:

~/g/s/g/c/golang-db-gateway-example git:master ❯❯❯ docker-compose up gateway                                                         ✱
mysql_server is up-to-date
Recreating gateway
Attaching to gateway
  • 写回答

3条回答 默认 最新

  • douqi3913 2016-03-15 11:58
    关注

    Actually you successfully got the Go server running. It wasn't hanging, just waiting for connections. Due to some quirks, there's no output: it didn't attempt to connect to the database, and logging statements were buffered.

    Try modifying gateway.go main:

    func main() {
        log.Println("Starting main...")
    
        conn := os.ExpandEnv("root:${MYSQL_SERVER_PASSWORD}@mysql_server:3306/${MYSQL_DATABASE}")
    
        var err error
        db, err = sql.Open("mysql", conn)
        if err != nil {
            log.Fatal(err)
        }
    
        log.Println("pinging", conn)
        if err := db.Ping(); err != nil {
            log.Fatal(err)
        }
    
        r := mux.NewRouter()
        r.HandleFunc("/todos", getTodos).Methods("GET")
    
        listen := ":8080"
        log.Printf("Listening on %s
    ", listen)
        log.Fatal(http.ListenAndServe(listen, r))
    }
    

    Running this version gives:

    $ docker-compose up gateway
    mysql_server is up-to-date
    Starting gateway
    Attaching to gateway
    gateway | 2016/03/15 10:58:05 Starting main...
    gateway | 2016/03/15 10:58:05 pinging root:@mysql_server:3306/sandbox
    gateway | 2016/03/15 10:58:05 default addr for network 'mysql_server:3306' unknown
    gateway | exit status 1
    gateway exited with code 1
    

    You should be good to go from there. Note:

    • docker-compose seems to buffer standard output until newline
    • log functions such as log.Print add newlines, fmt.Print doesn't
    • sql.Open doesn't connect to the database, use sql.Ping (see wiki)
    • MYSQL_SERVER_PASSWORD is missing
    • network type of the mysql connection string is missing (see examples)
    • start mysql server too
    • need to create new or mount existing database 'sandbox'

    Hope that helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接
  • ¥15 MATLAB中使用parfor,矩阵Removal的有效索引在parfor循环中受限制
  • ¥20 Win 10 LTSC 1809版本如何无损提升到20H1版本
  • ¥50 win10 LTSC 虚拟键盘不弹出
  • ¥30 微信小程序请求失败,网页能正常带锁访问
  • ¥15 Matlab求解微分方程,如何用fish2d进行预优?