Skip to content

Instantly share code, notes, and snippets.

@felipecruz91
Created December 23, 2022 22:46
Show Gist options
  • Save felipecruz91/eff2fd831ac01d7da042be684db7e36e to your computer and use it in GitHub Desktop.
Save felipecruz91/eff2fd831ac01d7da042be684db7e36e to your computer and use it in GitHub Desktop.
Go Dockerfile.template
# This Dockerfile has been generated automatically from the official Go template.
FROM {{or .BuildStage.From "golang:1.19.4-alpine3.16"}} AS builder
{{- if .BuildStage.Envs }}
{{- range $value := .BuildStage.Envs}}
ENV {{$value}}
{{- end}}
{{- end }}
{{- if .BuildStage.Deps }}
# Install the following dependencies
RUN apk update && apk add \
{{- $n := len .BuildStage.Deps}}
{{- range $i, $value := .BuildStage.Deps}}
{{$value}} {{- if ne (plus1 $i) $n}} \ {{- end}}{{- end}}
{{- end}}
# Set the current working directory inside the container
WORKDIR {{or .BuildStage.Workdir "/app"}}
# Copy the go.mod and go.sum files to the working directory
COPY go.mod go.sum ./
# Download all the dependencies
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go mod download
# Copy the rest of the source code to the working directory
COPY . .
# Build the Go app
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o {{.BinaryName}}
# Use the {{or .RuntimeStage.From "scratch"}} image as the final image
FROM {{or .RuntimeStage.From "scratch"}}
{{- if .RuntimeStage.Deps }}
# Install the following dependencies
RUN apk update && apk add \
{{- $n := len .RuntimeStage.Deps}}
{{- range $i, $value := .RuntimeStage.Deps}}
{{$value}} {{- if ne (plus1 $i) $n}} \ {{- end}}{{- end}}
{{- end}}
# Set the current working directory inside the container
WORKDIR {{or .RuntimeStage.Workdir "/"}}
# Copy the binary from the builder stage
COPY --from=builder {{or .BuildStage.Workdir "/app"}}/{{.BinaryName}} {{.BinaryName}}
# Run the binary when the container starts
ENTRYPOINT ["{{or .RuntimeStage.Workdir "/"}}{{.BinaryName}}"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment