如何从二进制文件在Docker上运行Go Server

时间:2018-07-16 09:17:33

标签: docker go binary

我一直在尝试制作一个Dockerfile,这将使我可以将我的go服务器构建为二进制文件,然后从头开始镜像或alpine运行它。该服务器在macOS 10.13.5上本地运行良好,当它不是来自Docker上的二进制文件时,我就使它可以工作。

我不断收到此错误:

  

standard_init_linux.go:190:exec用户进程导致“ exec格式错误”

我一直在四处搜寻,发现了一些有关系统架构的知识。我不确定如何检查这是否是错误和/或如何解决。

任何有关调试或可能修复的提示都将不胜感激。

我的Dockerfile:

FROM golang:1.10.3 as builder
WORKDIR /go/src/gitlab.com/main/server
COPY . .
RUN go get -d -v ./...
RUN CGO_ENABLED=0 GOOS=linux go build -a -o main .

FROM scratch
ADD main /
CMD ["/main"]

输出:

Building go
Step 1/9 : FROM golang:1.10.3 as builder
 ---> 4e611157870f
Step 2/9 : WORKDIR /go/src/gitlab.com/main/server
Removing intermediate container 20cd4d66008b
 ---> 621d9fc02dde
Step 3/9 : COPY . .
 ---> cab639571baf
Step 4/9 : RUN go get -d -v ./...
 ---> Running in 7681f9adc7b2
Removing intermediate container 7681f9adc7b2
 ---> 767a4c9dfb94
Step 5/9 : RUN go build -a -installsuffix cgo -o main .
 ---> Running in a6ec73121163
Removing intermediate container a6ec73121163
 ---> b9d7d1c0d2f9
Step 6/9 : FROM alpine:latest
 ---> 11cd0b38bc3c
Step 7/9 : WORKDIR /app
 ---> Using cache
 ---> 6d321d334b8f
Step 8/9 : COPY . .
 ---> 048a59fcdd8f
Step 9/9 : CMD ["/app/main"]
 ---> Running in d50d174644ff
Removing intermediate container d50d174644ff
 ---> 68f8f3c6cdf7
Successfully built 68f8f3c6cdf7
Successfully tagged main_go:latest
Creating go ... done
Attaching to go
go           | standard_init_linux.go:190: exec user process caused "exec format error"
go exited with code 1

1 个答案:

答案 0 :(得分:1)

正如@tgogos指出的那样,我是否需要使用第一步中构建的内容。

我的最终Dockerfile像这样以一些进一步的改进而结束:尽管重要的部分是倒数第二行:

FROM golang:1.10.3 AS build
WORKDIR /go/src/gitlab.com/main/server
COPY . .
RUN go get github.com/golang/dep/cmd/dep && \
      dep ensure && \
      rm -f schema/bindata.go && \
      go generate ./schema
RUN CGO_ENABLED=0 GOOS=linux go build -a -o main .

FROM alpine
RUN apk add --no-cache ca-certificates
COPY --from=build /go/src/gitlab.com/main/server/main .
CMD ["/main"]