如何运行使用go二进制文件创建的Docker容器?

I am trying to create a docker container with a Dockerfile and a go file binary.

I have two files in my folder: Dockerfile and main, where the latter is a binary of my simple go file.

Contents of Dockerfile:

FROM golang:1.11-alpine
WORKDIR /app
COPY main /app/
RUN ["chmod", "+x", "/app/main"]
ENTRYPOINT ["./main"]

I tried following steps:

  1. sudo docker build -t naive5cr .
  2. sudo docker run -d -p 8080:8080 naive5cr

The error which i see in thru "docker logs " :

standard_init_linux.go:207: exec user process caused "no such file or directory"

my go file content [i think it is irrelevant to the problem]:

func main() {
    http.HandleFunc("/", index)

    http.ListenAndServe(port(), nil)
}

func port() string {
    port := os.Getenv("PORT")
    if len(port) == 0 {
        port = "8080"
    }
    return ":" + port
 } 

the binary "main" runs as expected when run standalone. so there is no problem with the content of go file.

You need to compile with CGO_ENABLED=0 to prevent links to libc on Linux when networking is used in Go. Alpine ships with musl rather than libc, and attempts to find libc result in the no such file or directory error. You can verify this by running ldd main to see the dynamic links.

You can also build on an Alpine based host to link to musl instead of libc. The advantage of a completely statically compiled binary is the ability to run on scratch, without any libraries at all.

go compiles down to native code, so make sure to build your go code on the Docker image, instead of copying the binary to the docker image.

e.g.

FROM golang:1.11-alpine
WORKDIR /app
ADD . /app
RUN cd /app && go build -o goapp
ENTRYPOINT ./goapp

Also as a bonus, here is how to create really tiny Docker images with multistage Docker builds:

FROM golang:1.11-alpine AS build-env
ADD . /src
RUN cd /src && go build -o goapp

FROM alpine
WORKDIR /app
COPY --from=build-env /src/goapp /app/
ENTRYPOINT ./goapp