Ravindra BagaleCourses & study guides मराठी

Chapter 57: Docker Projects Part 1: Websites, Databases, LAMP, LEMP, WordPress, 3-Tier and Every Language with MySQL and MongoDB

DevOps

57.7 Project 7: Go with MySQL and MongoDB in a tiny distroless image

Friends, today we compile a Go rides API into a tiny distroless image with no shell. MySQL and MongoDB run beside it in Compose. The API checks the database door with a plain TCP dial from the standard library, serves rides from a seeded JSON file, and runs as nonroot. Type every command yourself.

What you will learn in this lesson

  1. Why Go apps fit multi-stage and distroless images.
  2. How a builder stage compiles a static binary.
  3. How distroless runs without a shell or package manager.
  4. How Compose runs MySQL or MongoDB beside the API.
  5. How to prove image size and the nonroot user.

1. Start from a real problem

Suppose we are at Ola and the platform team writes a rides API in Go because it is fast and uses little memory. Shipping a full Linux image for a single binary wastes hundreds of megabytes and leaves a shell an attacker could use.

So we use a multi-stage build: compile in golang:1.23, then copy only the binary into a distroless static image that has no shell and no package manager.

PhonePe and Razorpay style teams use the same idea for Go microservices: small attack surface, fast pulls, clear nonroot user. In this classroom build the API uses only the Go standard library so the lesson stays simple and safe.

Stage 1 golang:1.23compiles a static binaryCOPY --from=buildonly the binary movesStage 2 distrolessno shell, nonroot userComposeMySQL or Mongo beside the API
Picture 1: two stages to a tiny image

2. Write the Go API

Step 1: Project module

Why: A tiny HTTP API with the standard library.

What: go.mod names the module. main.go serves health and a rides list. Health dials the database TCP door. Rides come from a JSON file a seed job writes.

Example 1: Make folder and module

Type this:

mkdir -p rides-api && cd rides-api && docker run --rm -v "$PWD":/src -w /src golang:1.23 go mod init rides.local/api && cat go.mod

You will see:

module rides.local/api

go 1.23

What it means: Module file created without installing Go on the host.

Example 2: Show module path

Type this:

grep '^module' go.mod

You will see:

module rides.local/api

What it means: Local module name for this project.

Example 3: Confirm Go version in the builder

Type this:

docker run --rm golang:1.23 go version

You will see:

go version go1.23.2 linux/amd64

What it means: Builder image matches the Dockerfile.

Step 2: main.go routes

Why: Health dial and JSON rides.

What: GET /healthz dials DB_ADDR. GET /rides reads /data/rides.json. No third-party drivers in this classroom build keeps the binary and the lesson small.

Example 4: Write main.go

Type this:

printf '%s\n' 'package main' 'import (' '  "encoding/json"' '  "log"' '  "net"' '  "net/http"' '  "os"' '  "time"' ')' '' 'type Ride struct { ID string; City string }' '' 'func main() {' '  mux := http.NewServeMux()' '  mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {' '    addr := os.Getenv("DB_ADDR")' '    if addr == "" { http.Error(w, "DB_ADDR missing", 500); return }' '    c, err := net.DialTimeout("tcp", addr, 2*time.Second)' '    if err != nil { http.Error(w, err.Error(), 500); return }' '    c.Close(); w.Write([]byte("ok"))' '  })' '  mux.HandleFunc("/rides", func(w http.ResponseWriter, r *http.Request) {' '    b, err := os.ReadFile("/data/rides.json")' '    if err != nil { http.Error(w, err.Error(), 500); return }' '    w.Header().Set("Content-Type", "application/json")' '    w.Write(b)' '  })' '  log.Println("rides api on :8080")' '  log.Fatal(http.ListenAndServe(":8080", mux))' '}' > main.go && wc -l main.go

You will see:

28 main.go

What it means: Health dials TCP. Rides come from a file.

Example 5: Show the dial

Type this:

grep DialTimeout main.go

You will see:

c, err := net.DialTimeout("tcp", addr, 2*time.Second)

What it means: Standard library TCP check to MySQL or Mongo door.

Example 6: Show the rides file path

Type this:

grep rides.json main.go

You will see:

b, err := os.ReadFile("/data/rides.json")

What it means: Seed job will write this file into a shared volume.

3. Distroless multi-stage Dockerfile

Step 3: Two-stage Dockerfile

Why: Builder then distroless.

What: CGO_ENABLED=0 makes a static binary. The final image is gcr.io/distroless/static-debian12:nonroot. There is no shell to docker exec into.

Example 7: Write Dockerfile

Type this:

printf '%s\n' '# Stage 1: compile' 'FROM golang:1.23 AS build' 'WORKDIR /src' 'COPY go.mod ./' 'COPY main.go .' 'RUN CGO_ENABLED=0 GOOS=linux go build -o /rides ./' '' '# Stage 2: tiny runtime' 'FROM gcr.io/distroless/static-debian12:nonroot' 'COPY --from=build /rides /rides' 'USER nonroot:nonroot' 'EXPOSE 8080' 'ENTRYPOINT ["/rides"]' > Dockerfile && wc -l Dockerfile

You will see:

11 Dockerfile

What it means: Two FROM lines. Final stage has only the binary.

Example 8: Write .dockerignore

Type this:

printf '%s\n' '.git' '*.md' 'data/' > .dockerignore && cat .dockerignore

You will see:

.git
*.md
data/

What it means: Keep the build context small.

Example 9: Count FROM lines

Type this:

grep -c '^FROM ' Dockerfile

You will see:

2

What it means: Builder and distroless runtime.

Step 4: Build and prove size

Why: Small images pull fast.

What: Distroless plus one static binary should land near a dozen megabytes.

Example 10: Build rides:1.0

Type this:

docker build -t rides:1.0 .

You will see:

[+] Building ... FINISHED
 => naming to docker.io/library/rides:1.0

What it means: Image built.

Example 11: Show image size

Type this:

docker images rides:1.0 --format '{{.Repository}}:{{.Tag}} {{.Size}}'

You will see:

rides:1.0 8.7MB

What it means: About 9 MB. No shell, no package manager.

Example 12: Show the configured user

Type this:

docker image inspect rides:1.0 --format '{{.Config.User}}'

You will see:

nonroot:nonroot

What it means: Runs as the distroless nonroot user (uid 65532).

4. Run with MySQL beside the API

Normal alpine imagehas /bin/shdistroless imageno shell to execYou debug withlogs, metrics, local binary
Picture 2: no shell in the container

Step 5: MySQL Compose and seed

Why: Database plus JSON seed file.

What: MySQL holds the source rows. A one-shot seed container reads them with the mysql client and writes /data/rides.json for the API volume.

Example 13: Write init SQL and seed script

Type this:

mkdir -p db data && printf '%s\n' 'CREATE TABLE rides (id VARCHAR(20) PRIMARY KEY, city VARCHAR(40) NOT NULL);' 'INSERT INTO rides (id, city) VALUES ("r1", "Pune"), ("r2", "Mumbai");' > db/init.sql
printf '%s\n' '#!/bin/sh' 'mysql -hdb -urides -p"$DB_PASSWORD" rides -N -e "SELECT id, city FROM rides" | awk '\''BEGIN{print "["} {printf c "{\"id\":\"%s\",\"city\":\"%s\"}", $1, $2; c=","} END{print "]"}'\'' > /data/rides.json' 'wc -c /data/rides.json' > db/seed.sh && chmod 755 db/seed.sh && wc -l db/seed.sh

You will see:

6 db/seed.sh

What it means: Seed script turns SQL rows into JSON for the API.

Example 14: Write compose.mysql.yaml

Type this:

printf '%s\n' 'name: rides-mysql' 'services:' '  db:' '    image: mysql:8.4' '    environment:' '      MYSQL_DATABASE: rides' '      MYSQL_USER: rides' '      MYSQL_PASSWORD: ${DB_PASSWORD}' '      MYSQL_ROOT_PASSWORD: ${DB_ROOT_PASSWORD}' '    volumes:' '      - mysql-data:/var/lib/mysql' '      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql:ro' '    healthcheck:' '      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-uroot", "-p${DB_ROOT_PASSWORD}"]' '      interval: 5s' '      retries: 20' '' '  seed:' '    image: mysql:8.4' '    environment: [DB_PASSWORD]' '    volumes: ["./db/seed.sh:/seed.sh:ro", "rides-data:/data"]' '    entrypoint: ["/bin/sh", "/seed.sh"]' '    depends_on:' '      db: {condition: service_healthy}' '' '  api:' '    image: rides:1.0' '    ports: ["8080:8080"]' '    environment:' '      DB_ADDR: db:3306' '    volumes: ["rides-data:/data:ro"]' '    depends_on:' '      seed: {condition: service_completed_successfully}' '' 'volumes: {mysql-data:, rides-data:}' > compose.mysql.yaml
printf '%s\n' 'DB_PASSWORD=rides-pass' 'DB_ROOT_PASSWORD=root-pass' > .env && wc -l compose.mysql.yaml

You will see:

36 compose.mysql.yaml

What it means: MySQL, seed job and distroless API.

Example 15: Start and test

Type this:

docker compose -f compose.mysql.yaml up -d
sleep 20
curl -s http://localhost:8080/healthz
curl -s http://localhost:8080/rides

You will see:

ok
[{"id":"r1","city":"Pune"},{"id":"r2","city":"Mumbai"}]

What it means: TCP health to MySQL passed. Seeded rides returned.

Step 6: Prove there is no shell

Why: Distroless hardening.

What: docker exec with sh fails. That is expected. Debug with logs and by running the binary in the builder image.

Example 16: Try to open a shell

Type this:

docker compose -f compose.mysql.yaml exec api sh 2>&1 | head -2

You will see:

OCI runtime exec failed: ... executable file not found

What it means: No /bin/sh inside distroless.

Example 17: Read logs instead

Type this:

docker compose -f compose.mysql.yaml logs --tail 3 api

You will see:

rides api on :8080

What it means: Logs are your main window into the process.

Example 18: Confirm user

Type this:

docker inspect -f '{{.Config.User}}' $(docker compose -f compose.mysql.yaml ps -q api)

You will see:

nonroot:nonroot

What it means: Still nonroot at runtime.

5. Same binary with MongoDB

Step 7: Mongo Compose

Why: Change the neighbour database.

What: Seed writes the same JSON shape from mongosh. API still dials db:27017 and reads /data/rides.json.

Example 19: Write compose.mongo.yaml

Type this:

printf '%s\n' 'name: rides-mongo' 'services:' '  db:' '    image: mongo:7' '    volumes: [mongo-data:/data/db]' '    healthcheck:' '      test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand(\"ping\").ok"]' '      interval: 5s' '      retries: 20' '' '  seed:' '    image: mongo:7' '    volumes: ["rides-data:/data"]' '    depends_on:' '      db: {condition: service_healthy}' '    entrypoint: ["/bin/bash", "-c", "mongosh mongodb://db:27017/rides --eval '\''db.items.insertMany([{id:\"r9\",city:\"Bengaluru\"},{id:\"r8\",city:\"Hyderabad\"}])'\'' && mongosh mongodb://db:27017/rides --quiet --eval '\''const a=db.items.find({},{_id:0}).toArray(); print(JSON.stringify(a))'\'' > /data/rides.json"]' '' '  api:' '    image: rides:1.0' '    ports: ["8081:8080"]' '    environment:' '      DB_ADDR: db:27017' '    volumes: ["rides-data:/data:ro"]' '    depends_on:' '      seed: {condition: service_completed_successfully}' '' 'volumes: {mongo-data:, rides-data:}' > compose.mongo.yaml && docker compose -f compose.mongo.yaml up -d

You will see:

... Started

What it means: Mongo stack on host port 8081.

Example 20: Health on 8081

Type this:

curl -s http://localhost:8081/healthz

You will see:

ok

What it means: Same binary, Mongo door dial.

Example 21: List Mongo-seeded rides

Type this:

curl -s http://localhost:8081/rides

You will see:

[{"id":"r9","city":"Bengaluru"},{"id":"r8","city":"Hyderabad"}]

What it means: Documents seeded into the JSON file.

Step 8: Compare sizes and ports

Why: Why distroless wins.

What: One image serves both stacks. Size stays tiny.

Example 22: Image size again

Type this:

docker images rides:1.0 --format '{{.Size}}'

You will see:

8.7MB

What it means: Still tiny after both stacks used it.

Example 23: Both APIs up

Type this:

docker ps --format '{{.Names}} {{.Ports}}' | grep rides-

You will see:

rides-mysql-api-1 0.0.0.0:8080->8080/tcp
rides-mongo-api-1 0.0.0.0:8081->8080/tcp

What it means: Two projects, one image.

Example 24: History shows tiny final layers

Type this:

docker history rides:1.0 --format '{{.Size}}  {{.CreatedBy}}' | head -4

You will see:

8.5MB   ENTRYPOINT ["/rides"]
0B       USER nonroot:nonroot
...

What it means: Almost all size is the binary copy.

6. Mistakes and clean up

Step 9: Common mistakes

Why: Static build and health.

What: Forgetting CGO_ENABLED=0, using a shell-based healthcheck inside distroless, and pointing DB_ADDR at the wrong door are common.

Example 25: Why CGO_ENABLED=0

Type this:

grep CGO_ENABLED Dockerfile

You will see:

RUN CGO_ENABLED=0 GOOS=linux go build -o /rides ./

What it means: Static binary needs no libc from the runtime image.

Example 26: Healthcheck without shell inside

Type this:

echo 'Compose can healthcheck with curl from another container, or rely on /healthz from the load balancer'

You will see:

Compose can healthcheck with curl from another container, or rely on /healthz from the load balancer

What it means: Distroless has no wget or curl inside.

Example 27: Wrong DB_ADDR symptom

Type this:

docker compose -f compose.mysql.yaml exec db true && echo 'If DB_ADDR is db:9999, /healthz returns 500'

You will see:

If DB_ADDR is db:9999, /healthz returns 500

What it means: Door number must match MySQL 3306 or Mongo 27017.

Step 10: Clean up

Why: Remove both projects and the image.

What: down -v each file. Remove rides:1.0 when done.

Example 28: Stop MySQL project

Type this:

docker compose -f compose.mysql.yaml down -v

You will see:

... Removed

What it means: rides-mysql gone.

Example 29: Stop Mongo project

Type this:

docker compose -f compose.mongo.yaml down -v

You will see:

... Removed

What it means: rides-mongo gone.

Example 30: Remove image

Type this:

docker image rm rides:1.0

You will see:

Untagged: rides:1.0
Deleted: sha256:...

What it means: Disk space returned.

Step 11: Seed job pattern

Why: Databases write, API reads a file.

What: A one-shot seed container turns SQL or Mongo rows into JSON on a shared volume. The distroless API only needs to read a file and dial a door.

Example 31: Show seed depends_on

Type this:

grep -A2 'seed:' compose.mysql.yaml | head -5

You will see:

seed:
  image: mysql:8.4

What it means: Seed runs after db is healthy.

Example 32: Show API waits for seed

Type this:

grep -A2 'condition: service_completed_successfully' compose.mysql.yaml

You will see:

seed: {condition: service_completed_successfully}

What it means: API starts only after seed exits 0.

Example 33: Show shared volume

Type this:

grep rides-data compose.mysql.yaml | head -3

You will see:

      - rides-data:/data
    volumes: ["rides-data:/data:ro"]
volumes: {mysql-data:, rides-data:}

What it means: Same volume, seed writes, API reads read-only.

Step 12: When to add real drivers later

Why: Classroom versus production.

What: On your laptop later you can add the well-known Go MySQL and Mongo module paths and query with database drivers. The distroless build steps stay the same.

Example 34: Keep the Dockerfile identical

Type this:

grep ENTRYPOINT Dockerfile

You will see:

ENTRYPOINT ["/rides"]

What it means: Driver choice does not change the distroless final stage.

Example 35: Keep CGO off unless you must

Type this:

grep CGO_ENABLED Dockerfile

You will see:

RUN CGO_ENABLED=0 GOOS=linux go build -o /rides ./

What it means: Pure Go drivers keep CGO disabled.

Example 36: Same nonroot user

Type this:

grep USER Dockerfile

You will see:

USER nonroot:nonroot

What it means: Hardening stays. Only main.go imports grow.

Ravindra Bagale's Tip

Distroless means no shell inside production containers. Debug with logs, metrics and a local binary. Ola and PhonePe style Go teams accept this trade for a smaller attack surface.

Check yourself

Q1. Why use a multi-stage build for Go?

Compile in a fat builder image, then copy only the binary into a tiny runtime image.

Q2. What does distroless remove?

Shell, package manager and most OS tools, which shrinks size and attack surface.

Q3. Why set CGO_ENABLED=0?

So the binary is static and does not need libc from the runtime image.

Q4. Which user runs the container?

nonroot from the distroless image, usually uid 65532.

Q5. How does /healthz prove MySQL or Mongo is reachable?

It dials DB_ADDR with a TCP timeout using the Go standard library.

Q6. How do you debug without a shell?

Read container logs, use metrics, and run the binary in the builder image locally.

Friends, you shipped a Go API as a tiny distroless image, ran it as nonroot beside MySQL and MongoDB, and saw why there is no shell inside. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and rebuild the Dockerfile yourself. Next project: Java Spring Boot with MySQL and MongoDB.

Lab: try at home

  1. Create rides-api with go mod and main.go.
  2. Write the two-stage distroless Dockerfile.
  3. Build rides:1.0 and confirm a single-digit or low MB size.
  4. Start MySQL Compose and hit /healthz and /rides.
  5. Prove docker exec sh fails.
  6. Start Mongo Compose on 8081 and hit /rides.
  7. Clean up both projects and remove the image.

Recap

  • Go binaries fit multi-stage distroless images.
  • CGO_ENABLED=0 makes a static binary.
  • Distroless has no shell and runs as nonroot.
  • Compose can run MySQL or Mongo beside the API.
  • Debug with logs, not docker exec sh.
  • Small images pull faster and expose less.

Ravi Sir's Cards for this lesson

मराठी cards