Docker Build Golang App in Stages for Production
In this post we are going to dockerize our go app
it is very simple api server which is running on port 9900
this is very basic backend example which
package main
import (
"fmt"
"net/http"
)
func main() {
// Define a handler function for the root endpoint ("/")
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, World!")
})
// Start the server on port 8080
fmt.Println("Server listening on :9900")
http.ListenAndServe(":9900", nil)
}
Now create a Dockerfile in same directory and add the below content in that
we will build the docker image in stages.
In first stage we will compile our code and create a executable build file and in second stage we will run our executable go binary in alpine container, we will use alpine container to make our image smaller
Dockerfile will look like below one
FROM golang:1.21.0-alpine3.17 as builder
WORKDIR /src
COPY src .
RUN go mod tidy
RUN go build -o myapp .
FROM alpine:latest
WORKDIR /app
COPY --from=builder /src/myapp /app/myapp
RUN apk update
RUN apk add --no-cache libc6-compat
ENTRYPOINT [ "./myapp" ]
EXPOSE 9900/tcp
Now build image by using the below command
docker build -t my-example-app .
and to run it use below command
docker run -p 9900:9900 my-example-app
If you are facing permission issue use sudo
before the command
that’s it for this post