DEV Community

Rhonal Chirinos
Rhonal Chirinos

Posted on • Edited on

Build an API on a Docker image that is less than 20 MB

In this exercise, we aim to build a lightweight Dockerized API that weighs less than 20 MB. To achieve this, we'll use a multi-stage build and Alpine Linux — a minimal base image designed small containers. Our API will be written in Go.

Project Structure

exec01/
├── Dockerfile
├── go
│   ├── go.mod
│   └── main.go
Enter fullscreen mode Exit fullscreen mode
  • Dockerfile
FROM golang:1.24.3-alpine AS builder
ARG TARGETARCH
WORKDIR /app
COPY ./go .
RUN go build -o app && chmod +x app

FROM alpine:latest
WORKDIR /app 
COPY --from=builder /app/app /app/app
EXPOSE 8080
CMD ["/app/app"]
Enter fullscreen mode Exit fullscreen mode
  • Go Module File
module exec01/helloworld
go 1.24.3
Enter fullscreen mode Exit fullscreen mode
  • Main Application (Go)
package main

import (
  "fmt"
  "net/http"
)

func main() {
  http.HandleFunc("/", Handler)
  http.ListenAndServe(":8080", nil)
}

func Handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Hello, World!")
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)