Skip to content

Instantly share code, notes, and snippets.

@mahrous-amer
Created July 3, 2025 06:35
Show Gist options
  • Save mahrous-amer/2fe93146a0927427cd96876547378f76 to your computer and use it in GitHub Desktop.
Save mahrous-amer/2fe93146a0927427cd96876547378f76 to your computer and use it in GitHub Desktop.
Dynamic Dockerfile for any local Go project
ARG GO_VERSION=1.20
ARG BASE_IMAGE=golang:${GO_VERSION}-bullseye
ARG APP_NAME=app
ARG APP_PORT=3000
FROM ${BASE_IMAGE} AS build
WORKDIR /app
COPY go.mod go.sum ./
RUN --mount=type=cache,target=/go/pkg/mod \
--mount=type=cache,target=/root/.cache/go-build \
go mod download
FROM build AS dev
RUN go install github.com/cosmtrek/air@latest \
&& go install github.com/go-delve/delve/cmd/dlv@latest
COPY . .
CMD ["air", "-c", ".air.toml"]
FROM build AS build-production
# Non-root user
RUN useradd -u 1001 nobody
COPY . .
RUN go build \
-ldflags="-linkmode external -extldflags -static" \
-tags netgo \
-o ${APP_NAME}
FROM scratch
ENV GIN_MODE=release
WORKDIR /
COPY --from=build-production /etc/passwd /etc/passwd
COPY --from=build-production /app/${APP_NAME} /${APP_NAME}
USER nobody
EXPOSE ${APP_PORT}
CMD ["/${APP_NAME}"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment