This tutorial aims to guide you on how to containerize your Go applications using Docker. Containerization helps to ensure that your application runs the same way regardless of the environment it's in.
By the end of this tutorial, you will be able to:
Before we begin, ensure that you have the following installed:
Docker allows you to package your application and its dependencies in a virtual container that can run on any Linux or Windows server. This helps to eliminate the "it works on my machine" problem when collaborating with others.
Go, also known as Golang, is a statically typed, compiled language designed at Google. Go is robust and ideal for developing scalable and efficient software.
To containerize a Go application, you need to create a Dockerfile. A Dockerfile is a text document that contains all the commands needed to build a Docker image.
Let's go through the steps of dockerizing a simple Go application.
First, let's create a simple Go application. Create a file named main.go
and add the following code:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, you've requested: %s\n", r.URL.Path)
})
http.ListenAndServe(":8080", nil)
}
This application starts a simple HTTP server that returns a message with the requested URL path.
Now, let's create a Dockerfile for our Go application. Create a file named Dockerfile
in the same directory as your main.go
file and add the following:
# Use the official Golang image to create a build artifact.
FROM golang:1.16 as builder
# Copy local code to the container image.
WORKDIR /app
COPY . .
# Build the command inside the container.
RUN go build -v -o server
# Use the official lightweight Scratch image.
# https://hub.docker.com/_/scratch
FROM scratch
# Copy the binary to the production image from the builder stage.
COPY --from=builder /app/server /server
# Run the web service on container startup.
CMD ["/server"]
This Dockerfile creates a Docker image that runs our Go application.
Build the Docker image using the following command:
docker build -t go-app .
Run the Docker image using the following command:
docker run -p 8080:8080 go-app
You can now access the application at http://localhost:8080
.
In this tutorial, we've learned how to write a simple Go application and containerize it using Docker. We wrote a Dockerfile to create a Docker image for our application and ran the application in a Docker container.
To learn more about Docker and Go, you can check out the following resources:
Now, try the following exercises to deepen your understanding:
/time
endpoint.http://localhost:8080/time
.Solutions:
main.go
like this:http.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "The current time is: %s\n", time.Now())
})
docker build -t go-app .
and run it with docker run -p 8080:8080 go-app
.http://localhost:8080/time
to see the current time.