DEV Community

M
M

Posted on

Build tiny docker container for go app using multi-stage Dockerfile

Use latest version of golang as builder container

FROM golang:1.21-alpine as builder 
Enter fullscreen mode Exit fullscreen mode

Set workdir to /app

WORKDIR /app 
Enter fullscreen mode Exit fullscreen mode

Copy files from current dir to /app/*

COPY . . 
Enter fullscreen mode Exit fullscreen mode

Download mods

RUN go mod download 
Enter fullscreen mode Exit fullscreen mode

Build go app in build container

RUN CGO_ENABLED=0 go build -o /my-app 
Enter fullscreen mode Exit fullscreen mode

Use as small container as possible

FROM scratch 
Enter fullscreen mode Exit fullscreen mode

Copy root SSL sertificates to production container

COPY --from=alpine:latest /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 
Enter fullscreen mode Exit fullscreen mode

Copy our app from build container to production container

COPY --from=builder /my-app /my-app 
Enter fullscreen mode Exit fullscreen mode

Set entrypoint

ENTRYPOINT ["/my-app"] 
Enter fullscreen mode Exit fullscreen mode

to build our app run

docker build -t goapp . 
Enter fullscreen mode Exit fullscreen mode

and run it

docker run --rm -it goapp 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)