ga2-0d4166 / solution.md
mozoj4's picture
Initial commit from script
e441a55 verified
|
Raw History Blame Contribute Delete
6.99 kB

Question 10: Publish a Docker Space on Hugging Face with Environment Guardrails

Task

Deploy a containerized observability API to Hugging Face Spaces using Docker SDK with specific configuration requirements.

Solution Approach

Step 1: Create Hugging Face Space

  1. Go to https://huggingface.co/spaces/new
  2. Choose:
    • Name: ga2-0d4166 (exact)
    • License: Select any
    • SDK: Docker (not Streamlit/Gradio)
    • Visibility: Public
    • Space Hardware: CPU Basic (or suitable tier)
  3. Click Create

Step 2: Create Dockerfile

In your Space, create: Dockerfile

FROM python:3.11-slim

# Create non-root user (UID 1000)
RUN useradd -m -u 1000 appuser

WORKDIR /app

# Copy requirements
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY main.py .

# Set environment variables
ENV APP_PORT=7407

# Expose port
EXPOSE 7407

# Switch to non-root user
USER appuser

# Run application
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7407"]

Step 3: Create requirements.txt

Create: requirements.txt

fastapi==0.104.1
uvicorn[standard]==0.24.0
pydantic==2.5.0

Step 4: Create main.py

Create: main.py (FastAPI application)

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Optional, Dict, List
import json

app = FastAPI(title="Observability API", version="1.0.0")

class MetricsRequest(BaseModel):
    region: str
    latency_ms: float
    status: str

@app.get("/")
async def root():
    return {
        "name": "Observability API",
        "version": "1.0.0",
        "status": "operational"
    }

@app.get("/health")
async def health():
    return {"status": "healthy", "environment": "huggingface"}

@app.post("/metrics")
async def record_metrics(request: MetricsRequest):
    return {
        "recorded": True,
        "region": request.region,
        "latency_ms": request.latency_ms
    }

@app.get("/api/status")
async def api_status():
    return {
        "service": "observability-api",
        "deployment": "huggingface-spaces",
        "port": 7407
    }

Step 5: Configure README.md Frontmatter

Create/Update: README.md

---
title: GA2 Observability API
emoji: πŸš€
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7407
description: "deployment-ready-ga2-0d4166 - Containerized observability API with environment guardrails"
---

# GA2 Observability API

Deployment-ready containerized API with FastAPI and Docker.

## Features
- Health check endpoints
- Metrics recording
- Production-grade observability

## Environment
- Python 3.11
- FastAPI with Uvicorn
- Non-root user execution
- Port 7407 (configurable via ENV APP_PORT)

## Deployment

This Space is automatically built and deployed via Docker.

### Local Testing
```bash
docker build -t ga2-api .
docker run -p 7407:7407 ga2-api

API Endpoints

  • GET / - Service info
  • GET /health - Health check
  • POST /metrics - Record metrics
  • GET /api/status - API status

### Critical Frontmatter Fields

```yaml
sdk: docker                                    # Not streamlit/gradio
app_port: 7407                                # Exact port
description: "deployment-ready-ga2-0d4166"  # Must include this phrase

Step 6: Create Space Secret

  1. In your Space, go to Settings (gear icon)
  2. Scroll to Secrets
  3. Create new secret:
    • Name: GA2_TOKEN_6489 (exact)
    • Value: test-token-12345 (any value)
  4. Click Add secret

Step 7: Push to Hugging Face

# Create local repo if not from web UI
git clone https://huggingface.co/spaces/yourusername/ga2-0d4166
cd ga2-0d4166

# Add files
# - Dockerfile
# - requirements.txt
# - main.py
# - README.md (with proper frontmatter)

# Push
git add .
git commit -m "Initial deployment"
git push

Step 8: Monitor Build

  1. Go to your Space page
  2. Wait for Docker build to complete (may take 2-5 minutes)
  3. Space should auto-restart once built
  4. Check Runtime logs for any issues

Dockerfile Explanation

FROM python:3.11-slim         # Minimal Python image

RUN useradd -m -u 1000 ...   # Create non-root user (UID 1000)
ENV APP_PORT=7407             # Environment variable
EXPOSE 7407                    # Port declaration
USER appuser                   # Run as non-root user
CMD ["uvicorn", ...]          # Run FastAPI server

Security Guardrails

βœ… Non-root user: Runs as UID 1000 (security best practice)
βœ… Environment variable: APP_PORT configurable
βœ… Minimal base image: python:3.11-slim (smaller attack surface)
βœ… Read-only filesystem: Can be enforced in Space settings
βœ… Secret management: GA2_TOKEN_6489 securely stored

Hardware Options

  • CPU Basic: Shared CPUs, free tier (for this task)
  • CPU Upgrade: Dedicated CPUs, paid
  • GPU: For compute-intensive tasks

Verification Checklist

βœ… Space named exactly: ga2-0d4166
βœ… SDK: Docker (not Streamlit/Gradio)
βœ… Visibility: Public
βœ… README.md has correct frontmatter (sdk, app_port, description)
βœ… Dockerfile exists and builds successfully
βœ… main.py implements FastAPI server
βœ… requirements.txt has fastapi and uvicorn[standard]
βœ… Non-root user (UID 1000) configured
βœ… Port 7407 configured in Dockerfile and README
βœ… Secret GA2_TOKEN_6489 created
βœ… Space built and running (blue status)

Accessing Your Space

Once deployed:

https://huggingface.co/spaces/yourusername/ga2-0d4166

API accessible at:

https://yourusername-ga2-0d4166.hf.space

Test endpoints:

curl https://yourusername-ga2-0d4166.hf.space/health
curl -X POST https://yourusername-ga2-0d4166.hf.space/metrics \\
  -H "Content-Type: application/json" \\
  -d '{"region":"us","latency_ms":50.5,"status":"ok"}'

Troubleshooting

Build fails

  • Check Dockerfile syntax
  • Verify all files are present
  • Check logs in Space settings

App crashes

  • View runtime logs
  • Ensure port 7407 is correct
  • Check main.py syntax

Can't curl endpoint

  • Wait for Space to become "Running"
  • Check URL format
  • Verify Space is public

Final Submission

Paste your Space URL:

https://huggingface.co/spaces/yourusername/ga2-0d4166

Keep Space public until grading completes.

Grader will verify:

  1. Space exists and is public
  2. Docker SDK is configured
  3. README.md has correct frontmatter
  4. app_port is 7407
  5. description includes "deployment-ready-ga2-0d4166"
  6. Secret "GA2_TOKEN_6489" exists
  7. Dockerfile creates UID 1000 user
  8. Space builds and runs successfully