Table of Contents
Get your Go project structure ready
Using the basic build stage
Create a minimum runtime stage
Tips: Debugging and log support
Home Backend Development Golang How to build a multi-stage Docker build for Go

How to build a multi-stage Docker build for Go

Jul 09, 2025 am 01:19 AM

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.

How to build a multi-stage Docker build for Go

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.

How to build a multi-stage Docker build for Go

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.

How to build a multi-stage Docker build for Go

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:

How to build a multi-stage Docker build for Go
 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 install busybox 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Beginner's Guide to RimWorld: Odyssey
1 months ago By Jack chen
PHP Variable Scope Explained
4 weeks ago By 百草
Tips for Writing PHP Comments
3 weeks ago By 百草
Commenting Out Code in PHP
3 weeks ago By 百草

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1509
276
How to build a web server in Go How to build a web server in Go Jul 15, 2025 am 03:05 AM

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.

Go for Audio/Video Processing Go for Audio/Video Processing Jul 20, 2025 am 04:14 AM

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.

Go select with default case Go select with default case Jul 14, 2025 am 02:54 AM

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.

Developing Kubernetes Operators in Go Developing Kubernetes Operators in Go Jul 25, 2025 am 02:38 AM

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

Go REST API example Go REST API example Jul 14, 2025 am 03:01 AM

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.

How to make an HTTP request in Go How to make an HTTP request in Go Jul 14, 2025 am 02:48 AM

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

Go Query Optimization Techniques for PostgreSQL/MySQL Go Query Optimization Techniques for PostgreSQL/MySQL Jul 19, 2025 am 03:56 AM

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

Go defer statement explained Go defer statement explained Jul 14, 2025 am 02:57 AM

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.

See all articles