Home > Enterprise >  Docker Dev Environment for GO
Docker Dev Environment for GO

Time:11-03

What I want to do

I want to set up docker dev environment fo Go.

Code

// directory
project(absolute path: /Uses/[username]/project)
|--- app
|  |--- config
|  |  |___ config.go
|  |--- main.go
|  |___ config.ini 
|--- docker-compose.yml
|___ Dockerfile
// main.go
package main

import (
    "app/config"
    "fmt"
)

func main() {
    fmt.Println("Hello World")
    fmt.Println(config.Config.ApiKey)
    fmt.Println(config.Config.ApiSecrete)
}
// docker-compose.yml
version: '3.8'

services:
  app:
    build: .
    tty: true
    volumes:
    - ./app:/go/src/app

// Dockerfile
FROM golang:latest
RUN mkdir /go/src/app
WORKDIR /go/src/app
ENV GO111MODULE=on
ENV GOPATH /go
ADD ./app /go/src/app/

Dev Environment

When I run docker-compose exec app go env, I get

GOPATH="/go"
GOROOT="/usr/local/go"

Problem

When I run docker-compose up -d --build, I get package app/config is not in GOROOT (/usr/local/go/src/app/config). So, I can't import "app/config" in main.go file.

I want to know how import self-made package when I set up GO dev environment with docker.

CodePudding user response:

You can follow the go-env-series about how to use Docker to define your Go development environment in code.
Example: chris-crone/containerized-go-dev

The second article does mention go mod init, which helps with import path:

Let’s make the current directory the root of a module by using go mod init:

$ go mod init example.com/hello
go: creating new go.mod: module example.com/hello

The go.mod file only appears in the root of the module.

Packages in subdirectories have import paths consisting of the module path plus the path to the subdirectory.

For example, if we created a subdirectory world, we would not need to (nor want to) run go mod init there.
The package would automatically be recognized as part of the example.com/hello module, with import path example.com/hello/world.

CodePudding user response:

Thanks to you, I've solved this problem, so I'll share.

I run go mod init app, and go mod tidy.

Then, I change Dockerfile to set GO111MODULE=on.

version: '3.8'

services:
  app:
    build: .
    tty: true
    volumes:
    - ./app:/go/src/app
    environment:
      - "GO111MODULE=on"
// directory
project(absolute path: /Uses/[username]/project)
|--- app
|  |--- config
|  |  |___ config.go
|  |--- main.go
|  |--- config.ini 
|  |--- go.mod
|  |___ go.sum  
|--- docker-compose.yml
|___ Dockerfile

cf. 1 2

  • Related