Application Health Check with Golang and Multi-Stage Docker Build

Dockerfile to build and run the healthcheck app

Next step was to setup a build environment for the Healthcheck app, which I planned to have in Docker. I created a Dockerfile with the following content to build the application and being able to run it:

FROM golang:alpine as builderRUN apk update && apk add git && apk add ca-certificatesADD . /build/WORKDIR /buildRUN go get -d -vRUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o main .FROM scratchCOPY --from=builder /build/main /app/COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/WORKDIR /appCMD ["./main"]

Build a Go application

To build the application we need to create a main.go file and start with the following snippet:

docker build -t healthcheck .
docker run --rm healthcheck
Output of building and executing the Docker image
7.42 MB for the healthcheck Docker image

Code the final Healthcheck

The build environment is prepared now and we can code the Healthcheck app which will have the following requirements:

  • Have a route on /healthcheck
  • Checking the database and the web frontend
  • Give a json based Status code back
  • Status code 503 if something is broken, 200 if everything is fine
  1. In the main function we setup our Webservice listening on port 3001 and on /healthcheck
  2. The function handleRequest initializes a empty struct and calls the functions to check our MySQL DB and the WebUI interface
  3. In the checkWeb function we make a GET-Request to our WebUI and check if get a successfull HTTP Status code back
  4. The checkMysql function tries to connect to the database and pings it to evaluate if everything is fine
  5. Last step is to check if we have collected some error messages in our struct and set the Status code as state in the struct. Finally we return the serialized json output.
docker run --rm -p 3001:3001 healthcheckcurl localhost:3001/healthcheck
output of curl localhost:3001/healthcheck

Software Architect

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store