duanjiao6735
2019-05-04 18:19
浏览 131

在Docker中构建干净的Go应用程序

I'm trying to create Go web server into small Docker images. Ideally the clean image contains only the Go application itself (and maybe supporting web components, but not the Go-building environment).

Here is my Dockerfile:

# golang:latest as build-env
FROM golang:latest AS build-env

RUN mkdir /app
ADD . /app/
WORKDIR /app
RUN cd /app && GO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o myapp .
# go build -o myapp

FROM scratch
COPY --from=build-env /app/myapp /app/images /

EXPOSE 8080
ENTRYPOINT /myapp

It uses the Docker Builder Pattern and scratch image, which is a special docker image that's empty.

It builds OK, but when I run it, I'm getting:

docker: Error response from daemon: OCI runtime create failed: container_linux.go:344: starting container process caused "exec: \"/bin/sh\": stat /bin/sh: no such file or directory": unknown.

UPDATE:

So the ENTRYPOINT need to be changed to the exec form:

ENTRYPOINT ["/myapp"]

Having done that, I'm getting a new error:

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

Having use a small footprint Linux image as the base (i.e. Alpine Linux) instead of scratch wouldn't help either:

$ docker run -it -p 8080:8080 go-web-docker-small            
standard_init_linux.go:207: exec user process caused "no such file or directory"

$ docker run -it -p 8080:8080 go-web-docker-small /bin/sh -i 
standard_init_linux.go:207: exec user process caused "no such file or directory"

How to fix it? Thx!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douying0108 2019-05-04 19:18
    已采纳

    While building Dockerfile provided by you, I am getting following error:

    COPY failed: stat /var/lib/docker/overlay2/cc1f8144192760ce7bf9cda7a7dfd0af16065901594c38609c813ea103cfd8d7/merged/app/images: no such file or directory

    Fixed copy command and few others and image is building with following in Dockerfile

    # golang:latest as build-env
    FROM golang:latest AS build-env
    
    RUN mkdir /app
    ADD . /app/
    WORKDIR /app
    RUN cd /app && GO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o myapp .
    # go build -o myapp
    
    FROM scratch
    COPY --from=build-env /app/myapp .
    
    EXPOSE 8080
    ENTRYPOINT ["./myapp"]
    
    点赞 评论
  • dongzhuoxie1244 2019-05-04 19:52

    The last line of your Dockerfile is

    ENTRYPOINT /myapp
    

    There are two forms of the ENTRYPOINT (and CMD and RUN) instructions. An "exec form" looks like a JSON list, and provides an uninterpreted list of arguments to run as the main container process. A "shell form" does not look like a JSON list, and is implicitly wrapped in /bin/sh -c '...'.

    Your ENTRYPOINT uses the shell form, and a FROM scratch image doesn't have a shell, producing the error you get. You can change this to the exec form

    ENTRYPOINT ["/myapp"]
    
    点赞 评论