Optimizing Docker Builds: Everything You Need to Know
Extending the Base Image
In real-world scenarios, we often need to extend the base image by adding our application code, installing dependencies, and configuring the environment. To see an example of this, let's create a Dockerfile that builds a simple Go application.
Let's start by creating a simple Go application:
# Create a folder for the Go application
mkdir -p $HOME/my-golang-app
cd $HOME/my-golang-app
# Create a simple Go application
cat < main.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
EOF
In the next step, we will describe the process of creating a Dockerfile step-by-step.
Our Dockerfile will start with the Go base image:
# Use the specified image as the base
FROM golang:1.25-trixie
We want to copy the Go application into the image, then build it. To do this, we can use the COPY instruction:
# Set the working directory
WORKDIR /app
# Copy the local package files to the container's workspace
ADD . /app
Then we need to build the Go application:
# Build the Go app
RUN go mod init my-golang-app
RUN go build -o main .
Finally, we can run the application:
# Run the binary program produced by `go build`
CMD ["/app/main"]
The final Dockerfile can be created using the following command. Run this command in the same directory where main.go is located:
cd $HOME/my-golang-app
# Create the Dockerfile
cat << 'EOF' > Dockerfile
# Use the specified image as the base
FROM golang:1.21.3-alpine3.17
# Set the working directory inside the container
WORKDIR /app
# Copy the local package files to the container's workspacePainless Docker - 2nd Edition
A Comprehensive Guide to Mastering Docker and its EcosystemEnroll now to unlock all content and receive all future updates for free.
Hurry! This limited time offer ends in:
To redeem this offer, copy the coupon code below and apply it at checkout:
