'Golang executable not running in a multistage Dockerfile

I have the following Dockerfile:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

# PRODUCTION build
FROM golang:1.18-alpine as prd

COPY --from=build /app/server /app/server

CMD ["/app/server"]

The build is successful and when I run the image in a container, it exists immediately. I tried to run the image with CMD ["sleep", "100000"] , ssh into the container and run the executable manually inside - the same same happens - immediate exit w/o any output.

When I resort to a single stage for the Dockerfile it runs alright:

FROM golang:1.18 as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

CMD ["./server"]

But I want to build the final image from alpine, so it's smaller. Unfortunately, when I try to build the go app within alpine image:

FROM golang:1.18-alpine as build

WORKDIR /app

COPY . .

RUN CGO_ENABLED=0 go build -o server

I get the following error:

cgo: C compiler "gcc" not found: exec: "gcc": executable file not found in $PATH

So, I resorted to a multistage build.

I'm on a Mac, if that's relevant.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source