1

how to compile golang project with docker container? I want to compile and retrieve the project build, using docker cli

sample docker command

docker run -v $(pwd)/:/app -w /app -v $SSH_AUTH_SOCK:/tmp/ssh_auth.sock  -e SSH_AUTH_SOCK=/tmp/ssh_auth.sock  --name golanguser golang:1.17 sh -c "export GOPRIVATE=https://user:pass@bitbucket.org/repo/ && go build -o main bitbucket.org/repo/source"
1
  • go build creates an executable for your project, it doesn't run your code. Either call your executable after you built it, or go run. Note this doesn't create an optimized build. The best solution would be to have a Dockerfile directly in your repository, and build it from here (instead of fetching your code from bitbucket in the docker image).
    – KawaLo
    May 27, 2022 at 1:43

1 Answer 1

0

Building a go project is usually done in a multi-stage build

# syntax=docker/dockerfile:1

##
## Build
##
FROM golang:1.16-buster AS build

WORKDIR /app

COPY go.mod ./
COPY go.sum ./
RUN go mod download

COPY *.go ./

RUN go build -o /docker-gs-ping

##
## Deploy
##
FROM gcr.io/distroless/base-debian10

WORKDIR /

COPY --from=build /docker-gs-ping /docker-gs-ping

EXPOSE 8080

USER nonroot:nonroot

ENTRYPOINT ["/docker-gs-ping"]

With:

docker build -t docker-gs-ping:multistage -f Dockerfile.multistage .

That way, you can deploy the built application in the image of your choice, resulting in a markedly smaller image size to run.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.