Switch demo service to a Go binary on scratch

The python:3.12-slim base pushed a 30 MB layer that timed out on the way
to Harbor (Cloudflare 524). A static Go binary keeps the image near 5 MB
with the same endpoints, port and APP_MESSAGE variable.
This commit is contained in:
2026-10-23 08:50:10 +00:00
parent 2c21665d0e
commit fdb7ee666d
5 changed files with 66 additions and 47 deletions

View File

@@ -1,9 +1,14 @@
# The AISP build gateway only allows base images from approved mirrors, written with the # The AISP build gateway only allows base images from approved mirrors, written with the
# full host (docker.io/..., harbor.vts-ai.space/...). # full host (docker.io/..., harbor.vts-ai.space/...).
FROM docker.io/library/python:3.12-slim FROM docker.io/library/golang:1.23-alpine AS build
WORKDIR /src
COPY go.mod main.go ./
RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server .
WORKDIR /app # A static binary on scratch keeps the pushed image to a few MB; large layers time out
COPY app.py . # on the way to Harbor.
FROM scratch
COPY --from=build /out/server /server
# AISP enforces PodSecurity "restricted": run as a non-root UID on a port above 1024. # AISP enforces PodSecurity "restricted": run as a non-root UID on a port above 1024.
USER 10001 USER 10001
@@ -11,4 +16,4 @@ ENV PORT=8080 \
APP_MESSAGE="Hello from AISP" APP_MESSAGE="Hello from AISP"
EXPOSE 8080 EXPOSE 8080
CMD ["python", "-u", "app.py"] ENTRYPOINT ["/server"]

View File

@@ -6,8 +6,9 @@ Release → deploy.
- `GET /` trả JSON gồm `version`, `message` (từ biến `APP_MESSAGE`) và hostname của Pod. - `GET /` trả JSON gồm `version`, `message` (từ biến `APP_MESSAGE`) và hostname của Pod.
- `GET /healthz` dùng cho readiness check. - `GET /healthz` dùng cho readiness check.
- Lắng nghe cổng `8080`, chạy non-root (UID 10001). - Lắng nghe cổng `8080`, chạy non-root (UID 10001).
- Viết bằng Go, image cuối là `scratch` chỉ vài MB để push lên Harbor nhanh.
Thử thay đổi: sửa `VERSION` trong `app.py`, commit và push, rồi build lại trên console để thấy Thử thay đổi: sửa hằng `version` trong `main.go`, commit và push, rồi build lại trên console để thấy
phiên bản mới sau khi deploy. phiên bản mới sau khi deploy.
Chạy local: `docker build -t aisp-ci-demo . && docker run --rm -p 8080:8080 aisp-ci-demo` Chạy local: `docker build -t aisp-ci-demo . && docker run --rm -p 8080:8080 aisp-ci-demo`

42
app.py
View File

@@ -1,42 +0,0 @@
"""Minimal HTTP service for testing AISP's Gitea -> build -> release -> deploy flow."""
import json
import os
import socket
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
VERSION = "v1"
STARTED_AT = datetime.now(timezone.utc).isoformat()
class Handler(BaseHTTPRequestHandler):
def _send(self, status, body):
data = json.dumps(body).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def do_GET(self):
if self.path == "/healthz":
self._send(200, {"status": "ok"})
elif self.path == "/":
self._send(200, {
"service": "aisp-ci-demo",
"version": VERSION,
"message": os.environ.get("APP_MESSAGE", "Hello from AISP"),
"hostname": socket.gethostname(),
"startedAt": STARTED_AT,
})
else:
self._send(404, {"error": "not found"})
def log_message(self, fmt, *args):
print(f"{self.address_string()} {fmt % args}", flush=True)
if __name__ == "__main__":
port = int(os.environ.get("PORT", "8080"))
print(f"aisp-ci-demo {VERSION} listening on :{port}", flush=True)
ThreadingHTTPServer(("0.0.0.0", port), Handler).serve_forever()

3
go.mod Normal file
View File

@@ -0,0 +1,3 @@
module gitea.vts-ai.space/huulinhcvp/aisp-ci-demo
go 1.23

52
main.go Normal file
View File

@@ -0,0 +1,52 @@
// Minimal HTTP service for testing AISP's Gitea -> build -> release -> deploy flow.
package main
import (
"encoding/json"
"log"
"net/http"
"os"
"time"
)
const version = "v1"
func main() {
port := getenv("PORT", "8080")
hostname, _ := os.Hostname()
startedAt := time.Now().UTC().Format(time.RFC3339)
http.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
reply(w, http.StatusOK, map[string]string{"status": "ok"})
})
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
reply(w, http.StatusNotFound, map[string]string{"error": "not found"})
return
}
log.Printf("%s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
reply(w, http.StatusOK, map[string]string{
"service": "aisp-ci-demo",
"version": version,
"message": getenv("APP_MESSAGE", "Hello from AISP"),
"hostname": hostname,
"startedAt": startedAt,
})
})
log.Printf("aisp-ci-demo %s listening on :%s", version, port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func reply(w http.ResponseWriter, status int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
}
func getenv(key, fallback string) string {
if value := os.Getenv(key); value != "" {
return value
}
return fallback
}