xpt
xpt

Reputation: 22984

Building clean Go application in Docker

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!

Upvotes: 3

Views: 733

Answers (2)

David Maze
David Maze

Reputation: 158676

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"]

Upvotes: 10

Mayank Patel
Mayank Patel

Reputation: 8536

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"]

Upvotes: 3

Related Questions