0

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.

Milkncookiez
  • 6,817
  • 10
  • 57
  • 96
  • Try using `golang:1.18-alpine` as your build image. I've had issues when my build and runtime images were different Linux variants. Maybe that's what you already did when you say you tried using alpine. If so, just disregard. – Hans Kilian Apr 22 '22 at 16:00
  • Since Go is a compiled language, you don't need the Go toolchain to actually run the result. If your build is on a Debian-based image you might try making the final image be `FROM debian` or `FROM ubuntu` as well. – David Maze Apr 22 '22 at 16:04
  • @DavidMaze, should I then resolve the issue with `alpine` and make it build on an Alpine image? The weird thing is that [the official Docker page for building a Go app](https://docs.docker.com/language/golang/build-images/#create-a-dockerfile-for-the-application) uses an `alpine` image, but no mentions of the error. – Milkncookiez Apr 22 '22 at 16:07
  • Please provide a [mcve] that reproduces this issue, because the error appears to be in your Go code. – BMitch Apr 22 '22 at 16:12
  • One of the things that makes Alpine images tiny is a different C library, but this can result in strange compatibility problems. On the page you link to there are two examples: the first builds and runs the application in a `FROM golang:alpine` image; the second builds `FROM golang:buster` and then runs the application in a Debian-based image. I might follow @HansKilian's suggestion that the distributions should match. – David Maze Apr 22 '22 at 16:12
  • Could be a problem with file options? @Milkncookiez try doing `chmod +x /app/server` in the production image after copying the binary over – Suyash Medhavi Apr 24 '22 at 16:21

0 Answers0