-
Notifications
You must be signed in to change notification settings - Fork 3
/
Dockerfile
59 lines (45 loc) · 2.2 KB
/
Dockerfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# Dockerfile to generate docker image - the base docker image will copy the contents
# from the project root to docker container and generate a binary from it.
#
# Uses multi-stage build to reduce the size of docker image. The second image will use
# the binary generated by the first image
# Global arg to create second build image -- value will be `scratch` or `golang:{{ cookiecutter.go_version }}`
# depending on the build type needed
ARG final_image=scratch
# Can optionally use the Alpine Go image as the base - in general, images built on
# Apline are slimmer, but the variant is not officially support and is highly
# experimental - checkout https://github.com/golang/go/issues/19938 for details.
# Uncomment the line below to switch to the Alpine image as base (and comment the
# out the current base)
#
# FROM golang:{{ cookiecutter.go_version }}-alpine as builder
FROM golang:{{ cookiecutter.go_version }} as builder
# Setup environmet variables - chores.
ENV GO111MODULE=on \
CGO_ENABLED=0 \
GOOS=linux \
GOARCH=amd64
# Create a build directory if one does not exist, and use it as the work directory
WORKDIR "/src/__{{ cookiecutter.project_name.strip() }}__"
# Selectively copy the requirements into the image - using `*go.sum` prevents failure
# if the file does not exist!
COPY go.mod *go.sum ./
# Fetch all requirements and install them
RUN go mod download
# Copy remaining project files
COPY . .
# Generate a binary -- custom name to avoid collisions with existing files/directories
RUN go build -v -o "../__{{ cookiecutter.project_name.strip() }}_build_output__"
# Second stage - `scratch` for production builds, `golang:{{ cookiecutter.go_version }}` for debug builds
FROM ${final_image}
WORKDIR "/builds"
# Copy generated binary from previous image to this one - rename for readability
COPY --from=builder "/src/__{{ cookiecutter.project_name.strip() }}_build_output__" \
"./{{ cookiecutter.project_name.strip() }}"
# Set environment variables to distuinguish between build modes
ARG build_mode=production
ENV __BUILD_MODE__=${build_mode}
ENV ${build_mode}_mode=${build_mode}
# ^^ will be `debug_mode` or `production_mode`
# Run the binary
CMD ["./{{ cookiecutter.project_name.strip() }}"]