Home >Backend Development >Golang >Building Minimal Docker Images
Let's talk about Docker. Yes, this magical tool seems to be praised by every developer. It promises to make our lives easier and the deployment is smoother. But the problem is that your Docker mirror may be bloated. They are like a large suitcase you pack for weekend, full of unnecessary things, you can't even find what you need! This is like using a backpack instead of a handcase. Now, let's introduce to the Docker mirror
, this is the ultimate weight loss plan of your container. ?This is not just a few megers that reduce mirrors, but about creating streamlined, efficient, and fast containers. These containers are more easy to protect, deploy and expand. So, fasten the seat belt! We will explore the world of streamlined Docker mirrors, and use real examples and actual steps to enrich it.
What is the significance of streamlined Docker mirror? ?
----
If you are thinking, "Why pay so much? My application runs well", then the streamlined mirror is The reason for changing the rules of the game as follows:
2. Save cost?
3. Easy expansion?
Step by step: Construct a streamlined Docker mirror? ️
Your project folder should be shown below:
main.go
<code>/dockerized-golang-server |-- Dockerfile |-- go.mod |-- main.go</code>- A simple "Hello, World!" Server. Because why make life complicated?
<code>package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello, World!") }) http.ListenAndServe(":8080", nil) }</code>Secret: Streamline Dockerfile? ️
The following is the magic secret recipe of streamlined mirror constructed in multiple stages:
<code>module github.com/krishnaaher/golang-server go 1.23.3</code>Its working principle:
Construct
<code># 阶段1:构建Go应用程序 FROM golang:1.23.3-alpine AS builder WORKDIR /app COPY go.mod . COPY main.go . RUN go build -o /app/main # 阶段2:创建一个精简的运行时环境 FROM scratch COPY --from=builder /app/main /app/main # 运行应用程序的命令 CMD ["/app/main"]</code>: The first stage compiles the application. The second stage only includes the compiled binary files.
Verify whether your mirror is streamlined as you want:
3. Run the container
<code>docker build -t go-minimal-server .</code>
4. Test applications
<code>docker images</code>
Open your browser or use CURL for testing:
<code>REPOSITORY TAG IMAGE ID CREATED SIZE go-minimal-server latest 0b690a22521a Just now 11.7MB</code>
<code>/dockerized-golang-server |-- Dockerfile |-- go.mod |-- main.go</code>
The above is the detailed content of Building Minimal Docker Images. For more information, please follow other related articles on the PHP Chinese website!