Set the base image
use the official Go Docker image.
Set the working directory
set the working directory which defines the target location inside the container for all the subsequent instructions.
Copy and install dependencies
COPY go.mod go.sum ./
RUN go mod download
Use 𝘨𝘰.𝘮𝘰𝘥 to manage dependencies. By separating the dependencies from application source code you can take advantage of container layer caching. As long as you do not change the versions of libraries used by your application, the cached version of previously built layers will be reused, which will significantly shorten the build time. Additionally, including 𝘨𝘰.𝘴𝘶𝘮 file with checksums of all direct and indirect dependencies ensures that their content has not been modified.
Copy the application code
COPY *.go ./
Copy the source code of your application to the working directory created in the second step.
Compile the application
RUN go build -o /myapp
Compile your application from the source code and
Run as non-privileged user
Ensure that processes running in your container will be executed in non-privileged mode. Since a non-privileged user with id 1000 is already registered in the base Go image, just use it.
Set the entry command
this complete Dockerfile
FROM golang:1.21 WORKDIR /app COPY go.mod go.sum ./ RUN go mod download COPY *.go ./ RUN go build -o /myapp USER 1000 CMD ["/myapp"]