|
| 1 | +# Pin specific version for stability |
| 2 | +# Use separate stage for building image |
| 3 | +# Use debian for easier build utilities |
| 4 | +FROM golang:1.19-bullseye AS base-builder |
| 5 | + |
| 6 | +# Add non root user |
| 7 | +RUN useradd -u 1001 nonroot |
| 8 | + |
| 9 | +WORKDIR /app |
| 10 | + |
| 11 | +# Copy only files required to install dependencies (better layer caching) |
| 12 | +COPY go.mod go.sum ./ |
| 13 | + |
| 14 | +# Use cache mount to speed up install of existing dependencies |
| 15 | +RUN --mount=type=cache,target=/go/pkg/mod \ |
| 16 | + --mount=type=cache,target=/root/.cache/go-build \ |
| 17 | + go mod download |
| 18 | + |
| 19 | +# Dev stage with additional dev dependencies installed |
| 20 | +FROM base-builder AS dev |
| 21 | + |
| 22 | +# Install air for hot reload & delve for debugging |
| 23 | +RUN go install github.com/cosmtrek/air@latest && \ |
| 24 | + go install github.com/go-delve/delve/cmd/dlv@latest |
| 25 | + |
| 26 | +COPY . . |
| 27 | + |
| 28 | +CMD ["air", "-c", ".air.toml"] |
| 29 | + |
| 30 | +# Production builder stage to produce the static binaries |
| 31 | +FROM base-builder AS production-builder |
| 32 | + |
| 33 | +COPY . . |
| 34 | + |
| 35 | +# Compile healthcheck |
| 36 | +RUN go build \ |
| 37 | + -ldflags="-linkmode external -extldflags -static" \ |
| 38 | + -tags netgo \ |
| 39 | + -o healthcheck \ |
| 40 | + ./healthcheck/healthcheck.go |
| 41 | + |
| 42 | +# Compile application during build rather than at runtime |
| 43 | +# Add flags to statically link binary |
| 44 | +RUN go build \ |
| 45 | + -ldflags="-linkmode external -extldflags -static" \ |
| 46 | + -tags netgo \ |
| 47 | + -o api-golang |
| 48 | + |
| 49 | +# Use separate stage for deployable image |
| 50 | +FROM scratch AS production |
| 51 | + |
| 52 | +# Set gin mode |
| 53 | +ENV GIN_MODE=release |
| 54 | + |
| 55 | +WORKDIR / |
| 56 | + |
| 57 | +# Copy the passwd file |
| 58 | +COPY --from=production-builder /etc/passwd /etc/passwd |
| 59 | + |
| 60 | +# Copy the healthcheck binary from the build stage |
| 61 | +COPY --from=production-builder /app/healthcheck/healthcheck healthcheck |
| 62 | + |
| 63 | +# Copy the app binary from the build stage |
| 64 | +COPY --from=production-builder /app/api-golang api-golang |
| 65 | + |
| 66 | +# Use nonroot user |
| 67 | +USER nonroot |
| 68 | + |
| 69 | +# Indicate expected port |
| 70 | +EXPOSE 8080 |
| 71 | + |
| 72 | +CMD ["/api-golang"] |
0 commit comments