How to build a multi-stage Docker build for Go
Use multi-stage construction to optimize Docker image size for Go applications. The specific steps are: 1. Prepare the project structure to ensure that the location of main.go, go.mod and other files is correct and clearly compiled; 2. Set the basic construction stage, use golang mirror to compile statically linked binary files, and set CGO_ENABLED=0; 3. Create the run stage, use minimalist images such as scratch, distroless or alpine, and only copy binary files to achieve lightweight; 4. Optionally add debugging and log support, such as installing busybox in alpine or outputting logs to stdout/stderr to improve the convenience of pre-deployment testing.
You may have used Docker to build Go apps, but if you haven't used multi-stage build yet, you're missing out on a great way to optimize your image size. Go compilation itself does not require runtime dependencies, so the final image can only contain binary files without having to bring a bunch of build tools. Let’s talk about how to achieve this.

Get your Go project structure ready
Before writing a Dockerfile, make sure your Go project is structured clearly. Generally, you will have a main.go
file as the entry, or you may have multiple package files. The key is that you need to know the compile commands, such as:
go build -o myapp main.go
In addition, if you use module management ( go mod
), you must also ensure that go.mod
and go.sum
are in the correct position. This information affects the dependency download during the build process.

Using the basic build stage
The first step in multi-stage construction of Docker is usually the "builder" phase, and its task is to compile the executable file. You can use a complete Go image, such as golang:1.22
, to complete this step.
The example starts as follows:

FROM golang:1.22 AS builder WORKDIR /app COPY . . RUN CGO_ENABLED=0 go build -o myapp main.go
Here are a few details to note:
- Setting
CGO_ENABLED=0
can disable CGO. The binary compiled in this way is statically linked and is suitable for streamlined mirroring. -
-o myapp
specifies the output executable file name. - If you have multiple
.go
files, make sure the path is correct, or place it directly in the current directory.
Create a minimum runtime stage
After the build is completed, the next step is to create a running environment as small as possible. At this time, you can use minimalist images such as scratch
or alpine
.
For example:
FROM gcr.io/distroless/static-debian12 COPY --from=builder /app/myapp /myapp CMD ["/myapp"]
Here are a few choice points:
-
scratch
is the cleanest blank image for fully statically compiled Go programs. -
distroless
is a shell-free and package-free image provided by Google, which is more secure. - If you need to debug or view the logs, you can use
alpine
, which is more flexible but slightly larger.
Tips: Debugging and log support
Sometimes you may want to see what's going on in the container, especially during the pre-production testing phase. At this time, you can add a little debugging capability to the final image:
- Use an
alpine
image and installbusybox
so that you can at least go to the container to view files. - Add log output to the code and write the log to stdout/stderr to facilitate Docker log collection.
- If you use
distroless
, remember to copy configuration files, certificates and other resources in advance, because it does not have a shell, which is more troublesome to troubleshoot.
Basically that's it. The core idea of multi-stage construction is to "build and operate separately", use mirrors from different stages to perform their duties, and finally leave only what is really needed. The images built in this way are both safe and lightweight, and are very suitable for deployment in various environments.
The above is the detailed content of How to build a multi-stage Docker build for Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

It is not difficult to build a web server written in Go. The core lies in using the net/http package to implement basic services. 1. Use net/http to start the simplest server: register processing functions and listen to ports through a few lines of code; 2. Routing management: Use ServeMux to organize multiple interface paths for easy structured management; 3. Common practices: group routing by functional modules, and use third-party libraries to support complex matching; 4. Static file service: provide HTML, CSS and JS files through http.FileServer; 5. Performance and security: enable HTTPS, limit the size of the request body, and set timeout to improve security and performance. After mastering these key points, it will be easier to expand functionality.

The core of audio and video processing lies in understanding the basic process and optimization methods. 1. The basic process includes acquisition, encoding, transmission, decoding and playback, and each link has technical difficulties; 2. Common problems such as audio and video aberration, lag delay, sound noise, blurred picture, etc. can be solved through synchronous adjustment, coding optimization, noise reduction module, parameter adjustment, etc.; 3. It is recommended to use FFmpeg, OpenCV, WebRTC, GStreamer and other tools to achieve functions; 4. In terms of performance management, we should pay attention to hardware acceleration, reasonable setting of resolution frame rates, control concurrency and memory leakage problems. Mastering these key points will help improve development efficiency and user experience.

The purpose of select plus default is to allow select to perform default behavior when no other branches are ready to avoid program blocking. 1. When receiving data from the channel without blocking, if the channel is empty, it will directly enter the default branch; 2. In combination with time. After or ticker, try to send data regularly. If the channel is full, it will not block and skip; 3. Prevent deadlocks, avoid program stuck when uncertain whether the channel is closed; when using it, please note that the default branch will be executed immediately and cannot be abused, and default and case are mutually exclusive and will not be executed at the same time.

The most efficient way to write a KubernetesOperator is to use Go to combine Kubebuilder and controller-runtime. 1. Understand the Operator pattern: define custom resources through CRD, write a controller to listen for resource changes and perform reconciliation loops to maintain the expected state. 2. Use Kubebuilder to initialize the project and create APIs to automatically generate CRDs, controllers and configuration files. 3. Define the Spec and Status structure of CRD in api/v1/myapp_types.go, and run makemanifests to generate CRDYAML. 4. Reconcil in the controller

How to quickly implement a RESTAPI example written in Go? The answer is to use the net/http standard library, which can be completed in accordance with the following three steps: 1. Set up the project structure and initialize the module; 2. Define the data structure and processing functions, including obtaining all data, obtaining single data based on the ID, and creating new data; 3. Register the route in the main function and start the server. The entire process does not require a third-party library. The basic RESTAPI function can be realized through the standard library and can be tested through the browser or Postman.

The methods of initiating HTTP requests in Go are as follows: 1. Use http.Get() to initiate the simplest GET request, remember to handle the error and close the Body; 2. Use http.Post() or http.NewRequest() to send a POST request, and you can set JSON data or form data; 3. Set timeout, header and cookies, control Timeout and Header.Set to add custom headers through Client, and use CookieJar to automatically manage cookies; 4. Notes include having to close Body, non-req object, and setting User-Ag

TooptimizeGoapplicationsinteractingwithPostgreSQLorMySQL,focusonindexing,selectivequeries,connectionhandling,caching,andORMefficiency.1)Useproperindexing—identifyfrequentlyqueriedcolumns,addindexesselectively,andusecompositeindexesformulti-columnquer

The core function of defer is to postpone the execution of function calls until the current function returns, which is often used for resource cleaning. Specifically, it includes: 1. Ensure that files, network connections, locks and other resources are released in a timely manner; 2. The execution order is later-in-first-out (LIFO), and the last defined defer is executed first; 3. The parameters are determined when defer is defined, and evaluated during non-execution. If variable changes are needed, closures or pointers can be used; 4. Avoid abuse of defer in loops and prevent resource accumulation from being released in a timely manner.
