Skip to content

Instantly share code, notes, and snippets.

@syntaqx
Last active August 28, 2020 19:08
Show Gist options
  • Save syntaqx/7148a599c0f4f36da4fe5125e1bec228 to your computer and use it in GitHub Desktop.
Save syntaqx/7148a599c0f4f36da4fe5125e1bec228 to your computer and use it in GitHub Desktop.
# Accept image version tags to be set as a build arguments
ARG GO_VERSION=1.11
ARG ALPINE_VERSION=3.8
# Throw-away builder container
FROM golang:${GO_VERSION}-alpine${ALPINE_VERSION} AS builder
# Install build and runtime dependencies
# - Git is required for fetching Go dependencies
# - Certificate-Authority certificates are required to call HTTPs endpoints
# - UPX for packing the executable
RUN apk add --no-cache git ca-certificates upx
# Normalize the base environment
# - CGO_ENABLED: to build a statically linked executable
# - GO111MODULE: force go module behavior and ignore any vendor directories
ENV CGO_ENABLED=0 GO111MODULE=on
# Set the builder working directory
WORKDIR /go/src/github.com/syntaqx/example
# Fetch modules first. Module dependencies are less likely to change per build,
# so we benefit from layer caching
COPY ./go.mod ./*.sum ./
RUN go mod download
# Import the remaining source from the context
COPY . /go/src/github.com/syntaqx/example
# Build a statically linked executable and pack it
RUN go build -a -installsuffix cgo -ldflags '-s' -o ./bin/example ./cmd/example
RUN upx -qqq ./bin/example
# Runtime container
FROM alpine:${ALPINE_VERSION}
# Copy the binary and sources from the builder stage
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
COPY --from=builder /go/src/github.com/syntaqx/example/bin/example ./example
# Create a non-root runtime user
RUN addgroup -S example && adduser -S -G example example && chown -R example:example ./example
USER example
# Document the service listening port(s)
EXPOSE 8080
# Executing container default command
CMD ["./example"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment