将go app部署到docker时遇到问题

Hi I am pretty new to go, and this is my first time working with docker to package an app into a container. I am working on a linux VM where the app is located under dir: /home/core/app/app-name In the dir app-name there is the main.go program and the Dockerfile. The Dockerfile contains this:

FROM golang:latest
RUN mkdir /app
ADD . /home/core/app/app-name
WORKDIR /app/app-name
RUN go build -o main .
CMD ["/app/main"]
EXPOSE 8080

I have tried running from dir /home/core/app/app-name:

docker build -t app-image .

But I got this error:

can't load package: package .: no buildable Go source files in /app/stars-app The command '/bin/sh -c go build -o main .' returned a non-zero code: 1

What am I doing wrong?

Edit: I got was able to build the image on my windows machine with the Dockfile:

FROM golang:latest
Add . /app/app-name
EXPOSE 8080
CMD ["/app/app-name/main"]

And by running:

docker build -t star-image .

I can see the image when I run "docker images", but when I try to run it using:

docker run -p 3000:8080 --name goapp --rm app-name

I get this error:

docker: Error response from daemon: Container command '/app/app-name/main' not found or does not exist..

This might work for you...

  • The GOPATH for the image is set to /go
  • install your source(s) under /go/src
  • given the gopath is set and sources are within the GOPATH
  • setting the working directory to /app
  • execute the build and the output should be present in the working directory

Dockerfile

FROM golang:latest
ADD ./app /go/src/app
RUN mkdir /app
WORKDIR /app
RUN go build -o main app/app-name
CMD ["/app/main"]
EXPOSE 8080

app/app-name/main.go

package main

import "fmt"

func main() {
    fmt.Printf("hello, world
")
}

docker build -t app-image .
docker run app-image

output

hello, world