feat: add Docker Compose developer environment with Makefile shortcuts (M4)

- Root docker-compose.yml: backend (python:3.11-slim) + frontend
  (multi-stage node build -> nginx:alpine) on the newzy-network bridge
  network, frontend waits for the backend health check
- Persistent SQLite via bind mount ./data/db -> /app/data/db
- .env / .env.example documenting DATABASE_URL, DEBUG,
  BACKEND_CORS_ORIGINS and FRONTEND_API_URL
- Makefile: dev, stop, restart, build, logs, status, backend-start,
  frontend-start, test, e2e, shell-backend, shell-frontend, clean
- data/.gitignore keeps the data/ structure in git while excluding the
  database; root .gitignore drops the overly broad data/ rule and adds
  docker-compose.override.yml
- backend: .gitignore covers .env.*, Dockerfile sets unbuffered python
  and pre-creates the db volume dir; frontend: new .dockerignore
- README: full Docker setup docs (prerequisites, quick start, services,
  ports, network/storage, env vars, Makefile reference, troubleshooting)
This commit is contained in:
Daniel Samson committed 2026-10-30 15:35:08 +00:00
1 parent 9144411e0f
commit ed7b30438e
11 files changed
+653 -15

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
# newzy — environment variable template.
#
# Copy to `.env` and adjust as needed:
#
# cp .env.example .env
#
# `docker compose` in this directory reads `.env` automatically. `.env` is
# excluded from version control (see .gitignore) — never commit secrets.
# The backend's own defaults are documented in `backend/.env.example`.
# --- Database -------------------------------------------------------------
# SQLite database location (SQLAlchemy URL, relative to the backend's
# working directory). Inside the Docker image this resolves to
# /app/data/db/newzy.db, which is bind-mounted to ./data/db on the host.
DATABASE_URL=sqlite:///./data/db/newzy.db
# --- Backend ----------------------------------------------------------------
# Enable debug mode (verbose logs; keep off in production).
DEBUG=false
# Comma-separated list of origins the backend allows for CORS. The Docker
# frontend proxies /api (same-origin, no CORS needed); this mainly matters
# when developing the frontend directly on http://localhost:5173.
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
# --- Frontend ----------------------------------------------------------------
# Base URL the frontend uses to reach the backend API.
# /api -> relative (recommended: the Vite dev server and the
# Docker Nginx config both proxy /api to the backend)
# http://host:port -> absolute (cross-origin; the origin must be listed in
# BACKEND_CORS_ORIGINS)
FRONTEND_API_URL=/api
+4 -2
View File
@@ -43,8 +43,10 @@ coverage/
.DS_Store
Thumbs.db
# Local data / uploads
data/
# Docker (local per-developer overrides; .dockerignore files are committed)
docker-compose.override.yml
# Local data / uploads (data/ is managed by data/.gitignore)
uploads/
*.sqlite
*.db
+60
View File
@@ -0,0 +1,60 @@
# newzy — development shortcuts (docker compose under the hood).
# Run `make help` (or just `make`) for the list of targets.
COMPOSE ?= docker compose
.DEFAULT_GOAL := help
.PHONY: help dev stop restart build logs status backend-start frontend-start \
test test-frontend test-backend e2e shell-backend shell-frontend clean
help: ## Show this help
@grep -E '^[a-zA-Z_-]+:.*?## ' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf " \033[36m%-15s\033[0m %s\n", $$1, $$2}'
dev: ## Build (if needed) and start both services in the background
$(COMPOSE) up -d --build
stop: ## Stop and remove containers (local data in ./data is kept)
$(COMPOSE) down
restart: ## Recreate and start both services
$(COMPOSE) down
$(COMPOSE) up -d --build
build: ## Rebuild all images from scratch (no cache)
$(COMPOSE) build --no-cache
logs: ## Follow the logs of both services
$(COMPOSE) logs -f backend frontend
status: ## Show the status of both services
$(COMPOSE) ps
backend-start: ## Build (if needed) and start the backend only
$(COMPOSE) up -d backend
frontend-start: ## Build (if needed) and start the frontend only
$(COMPOSE) up -d frontend
test: test-frontend test-backend ## Run all unit tests (frontend + backend)
test-frontend: ## Run frontend unit tests (requires Node.js 18+)
cd frontend && npm run test
test-backend: ## Run backend tests (uses backend/.venv if present, else system pytest)
cd backend && if [ -x .venv/bin/pytest ]; then .venv/bin/pytest; else pytest; fi
e2e: ## Run Playwright E2E tests (frontend/playwright; API calls are mocked)
cd frontend && npm run e2e
shell-backend: ## Open a shell inside the running backend container
$(COMPOSE) exec backend bash
shell-frontend: ## Open a shell inside the running frontend container
$(COMPOSE) exec frontend sh
clean: ## Stop everything; remove containers, volumes and local data
$(COMPOSE) down -v --remove-orphans
rm -rf data/
git checkout -- data/ 2>/dev/null || true
docker image prune -f
+103 -7
View File
@@ -11,7 +11,8 @@
| M1 | Git project setup | Done |
| M2 | Backend setup (FastAPI) | Done |
| M3 | Frontend setup (React + Vite) | Done |
| M4+ | News application features | Planned |
| M4 | Developer environment (Docker) | Done |
| M5+ | News application features | Planned |
See [milestones/](milestones/) for milestone prompts and progress tracking.
@@ -44,17 +45,112 @@ git push -u origin feature/<short-description>
Full contribution guidelines, including branching, merging, and rebase workflows, are in [CONTRIBUTING.md](CONTRIBUTING.md).
## Running the application
## Developer environment (Docker Compose)
The repository root ships a complete Docker Compose setup: one command starts
the FastAPI backend and the Nginx-served production frontend, with a
persistent SQLite database on the host.
### Prerequisites
- **Docker** (Docker Desktop or the docker engine + compose plugin v2), with the daemon running
- Optional (only for `make test` outside Docker): **Node.js 18+** and **Python 3.11+**
### Quick start
```bash
# Full stack (backend :8000 + frontend :3000)
docker compose up --build
# 1. Configure the environment (defaults are fine for local development)
cp .env.example .env
# 2. Build (if needed) and start both services in the background
make dev
# 3. Open the application
# Frontend: http://localhost:3000
# Backend: http://localhost:8000 (Swagger docs: http://localhost:8000/api/v1/docs)
# 4. Stop everything (the database in ./data is kept)
make stop
```
Or run each half locally — see the component READMEs for details:
### Services
- [frontend/README.md](frontend/README.md) — `npm run dev` (port 5173)
- [backend/README.md](backend/README.md) — `uvicorn main:app --reload` (port 8000)
| Service | Build context | Image base | What it does |
| ---------- | ------------- | ----------------- | -------------------------------------------------------- |
| `backend` | `./backend` | `python:3.11-slim`| FastAPI app (uvicorn), creates the SQLite schema on startup |
| `frontend` | `./frontend` | `node:20-alpine` → `nginx:1.27-alpine` (multi-stage) | Builds the Vite bundle, serves it via Nginx with SPA routing and an `/api` proxy to the backend |
### Port mappings
| Host port | Container | Service |
| --------- | --------- | -------- |
| `3000` | `80` | frontend (Nginx) |
| `8000` | `8000` | backend (uvicorn) |
### Networking and storage
- Both services share the bridge network `newzy-network` (subnet `172.28.0.0/16`),
so the frontend reaches the backend by service name (`http://backend:8000`).
- The SQLite database is stored on the host at [`data/db/newzy.db`](data/) via a
bind mount (`./data/db` → `/app/data/db`). It is excluded from version control
(see `data/.gitignore`) and survives `make stop`/`make restart`.
- `frontend` only starts once `backend` reports healthy (`/health`), so
`docker compose up` never serves a frontend with a dead API.
### Environment variables
`docker compose` reads [`.env`](.env) from the project root (template:
[`.env.example`](.env.example)). Never commit `.env` or real secrets.
| Variable | Description | Default | Required |
| --------------------- | ---------------------------------------- | --------------------------------------------------- | -------- |
| `DATABASE_URL` | SQLite database path (SQLAlchemy URL) | `sqlite:///./data/db/newzy.db` | Yes |
| `DEBUG` | Debug mode flag | `false` | No |
| `BACKEND_CORS_ORIGINS`| Comma-separated allowed CORS origins | `http://localhost:3000,http://localhost:5173` | No |
| `FRONTEND_API_URL` | Backend API base URL (relative or absolute) | `/api` | No |
### Makefile shortcuts
| Command | What it does |
| ---------------------- | ------------------------------------------------------- |
| `make dev` | Build (if needed) and start both services in the background |
| `make stop` | Stop and remove containers (data kept) |
| `make restart` | Recreate and start both services |
| `make build` | Rebuild all images from scratch |
| `make logs` | Follow logs of both services |
| `make status` | Show service status |
| `make backend-start` | Start the backend only |
| `make frontend-start` | Start the frontend only |
| `make test` | Run all unit tests (frontend vitest + backend pytest) |
| `make e2e` | Run Playwright E2E tests (API calls mocked) |
| `make shell-backend` | Open a shell in the backend container |
| `make shell-frontend` | Open a shell in the frontend container |
| `make clean` | Stop everything, remove containers, volumes and `data/` |
### Troubleshooting
- **Port already in use** (`bind: address already in use`): stop the other
process (`lsof -i :3000` / `lsof -i :8000`) or change the host port in
`docker-compose.yml` (e.g. `"3001:80"`).
- **Frontend starts but shows errors / 502 on API calls**: the backend is not
healthy yet — check `make logs backend`. The frontend waits for the backend
health check on startup; after a slow start, reload the page.
- **`docker compose` not found**: install the Compose v2 plugin
(`docker compose version` must print a version).
- **Database reset**: `make clean` removes `data/` (including the SQLite file);
tables are recreated on the next backend start.
- **Slow builds on first run**: the first `make dev` pulls the base images and
installs dependencies (~5 minutes). Subsequent builds use the Docker layer
cache and finish in seconds.
- **Ownership issues in `data/`** (e.g. after running Docker as root): restore
with `sudo chown -R $(id -un):$(id -gn) data/`.
- **Windows**: use WSL2 for best performance; **macOS**: allow Docker Desktop
sufficient disk space (50 GB+ recommended).
### Running without Docker
- Frontend: [`frontend/README.md`](frontend/README.md) — `npm run dev` (port 5173, proxies `/api` to :8000)
- Backend: [`backend/README.md`](backend/README.md) — `uvicorn main:app --reload` (port 8000)
## Documentation
+3 -1
View File
@@ -3,8 +3,10 @@ __pycache__/
*.py[cod]
*.egg-info/
# Environment files
# Environment files (keep the committed template)
.env
.env.*
!.env.example
.venv/
venv/
+13 -3
View File
@@ -1,15 +1,25 @@
# newzy backend — FastAPI + SQLite.
# Orchestration lives in the repository root: docker-compose.yml.
FROM python:3.11-slim
# Unbuffered logs, no .pyc files in the image, no pip cache.
ENV PYTHONUNBUFFERED=1 \
PYTHONDONTWRITEBYTECODE=1 \
PIP_NO_CACHE_DIR=1
WORKDIR /app
# Install dependencies first to leverage Docker layer caching
# Install dependencies first to leverage Docker layer caching.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
# Copy application code (dev-only files excluded by .dockerignore).
COPY . .
# SQLite database lives on a mounted volume (see docker-compose.yml)
# The SQLite database lives on a bind-mounted volume (see docker-compose.yml);
# ensure the directory exists even before the volume is attached.
RUN mkdir -p /app/data/db
VOLUME /app/data/db
# Expose port
+6
View File
@@ -0,0 +1,6 @@
# Exclude everything under data/ from version control (SQLite database,
# uploads, ...) except the keep file below, so the directory structure
# (data/db/) survives a fresh clone.
*
!.gitignore
!keep_files.txt
+4
View File
@@ -0,0 +1,4 @@
# This file is tracked by git so the data/ directory structure (data/db/)
# is preserved in fresh clones. Everything else under data/ — the SQLite
# database (data/db/newzy.db), uploads, and other local state — is ignored
# by data/.gitignore and recreated at runtime.
+39 -2
View File
@@ -1,23 +1,60 @@
# newzy — full application stack (FastAPI backend + Nginx frontend).
#
# make dev # build (if needed) and start both services in the background
# make stop # stop and remove the containers (local data is kept)
# make clean # stop everything and remove containers, volumes and data/
#
# Environment variables are read from `.env` in this directory (template:
# `.env.example`). See README.md for the complete developer documentation.
#
# The `version` key is intentionally omitted: it is obsolete in Compose v2
# and only produces a deprecation warning.
services:
backend:
build: ./backend
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
# Persistent SQLite database: ./data/db on the host -> /app/data/db
# inside the container (excluded from git, see data/.gitignore).
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
healthcheck:
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
interval: 30s
timeout: 5s
retries: 3
start_period: 10s
networks:
- newzy-network
restart: unless-stopped
frontend:
build: ./frontend
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:80"
depends_on:
backend:
condition: service_healthy
networks:
- newzy-network
restart: unless-stopped
networks:
newzy-network:
driver: bridge
ipam:
config:
- subnet: 172.28.0.0/16
volumes:
db-data:
name: newzy-db-data
+18
View File
@@ -0,0 +1,18 @@
# Keep the image small: exclude dev-only files from the build context.
node_modules/
dist/
coverage/
test-results/
playwright-report/
playwright/.cache/
.env
.env.*
!.env.example
.git/
.gitignore
Dockerfile
.dockerignore
docker-compose.yml
README.md
*.log
.DS_Store
@@ -0,0 +1,372 @@
# M4: Setup Developer Environment
## Prompt
Set up a complete developer environment for **newzy** news web application with Docker Compose orchestration. Follow these steps:
1. Create `docker-compose.yml` at project root (`newzy/docker-compose.yml`) with all services:
```yaml
version: '3.8'
services:
backend:
build: ./backend
ports:
- "8000:8000"
volumes:
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
frontend:
build: ./frontend
ports:
- "3000:80"
depends_on:
- backend
networks:
newzy-network:
driver: bridge
volumes:
db-data:
```
2. Create `.env.example` file documenting all required environment variables:
- DATABASE_URL (SQLite path)
- DEBUG (boolean, optional)
- BACKEND_CORS_ORIGINS (comma-separated, default: http://localhost:3000)
- FRONTEND_API_URL (relative /api or absolute)
3. Create `.env` file with default development values:
```bash
DATABASE_URL=sqlite:///./data/db/newzy.db
DEBUG=false
BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
FRONTEND_API_URL=/api
```
4. Update `backend/.gitignore` to exclude `.env` and production data:
```python
.env
.env.*
data/
```
5. Create development scripts in project root using Makefile or shell script:
- `dev` - Start both services in background
- `stop` - Stop all services
- `restart` - Restart all services
- `backend-start` - Start backend only
- `frontend-start` - Start frontend only
- `test` - Run all tests (unit + E2E)
- `clean` - Remove containers and volumes
6. Add `Makefile` for command shortcuts:
```makefile
.PHONY: dev stop restart backend-start frontend-start test clean
dev:
docker compose up -d --build
stop:
docker compose down
restart:
docker compose down
docker compose up -d --build
backend-start:
docker compose up -d backend
frontend-start:
docker compose up -d frontend
test:
npm run test # frontend
cd backend && pytest # backend
clean:
docker compose down -v
rm -rf data/
docker image prune -f
```
7. Create `backend/Dockerfile` with development optimizations:
- Copy only required files
- Install dependencies efficiently
- Use slim Python base image
- Expose port 8000
8. Update `frontend/Dockerfile` to use production Nginx:
- Multi-stage build (build stage + nginx serve stage)
- Nginx configuration for SPA routing
- Production-optimized static file serving
9. Create `.gitignore` at project root excluding:
```
# Dependencies
node_modules/
*.egg-info/
# Environment files
.env
.env.local
.env.*.local
# IDE settings
.idea/
.vscode/
*.swp
*.swo
# Docker artifacts (optional)
.dockerignore
docker-compose.override.yml
```
10. Create `data/.gitignore` to exclude SQLite database from version control:
```
*
!keep_files.txt
```
11. Document setup process in `README.md`:
- Prerequisites (Docker, Node.js 18+)
- Quick start commands
- Service descriptions
- Port mappings
- Network configuration
- Troubleshooting guide
12. Create `.dockerignore` files for both backend and frontend to exclude unnecessary files during builds:
```
.git/
.env
__pycache__/
*.pyc
node_modules/
dist/
.pytest_cache/
```
Remember: Focus ONLY on developer environment setup. No application code changes required.
## Description
This milestone sets up a complete Docker Compose development environment for the newzy news web application. The scope includes orchestrating both backend and frontend services, environment variable management, and streamlined development commands—no application logic changes or business feature implementation.
**Purpose**: Provide developers with a consistent, reproducible local development environment using Docker that matches the production setup as closely as possible.
**Target Audience**: Developers joining the project who need quick access to running services without manual installation of Python, Node.js, databases, or Nginx.
**Expected Outcomes**: A working docker-compose.yml at project root that can start all services with a single command, proper environment configuration, and development workflow automation via Makefile.
## Acceptance Criteria
- [ ] `docker-compose.yml` at project root configures both backend and frontend services
- [ ] Backend service builds from `./backend` directory
- [ ] Frontend service builds from `./frontend` directory
- [ ] Port mappings configured: 3000 for frontend, 8000 for backend
- [ ] Docker network defined for inter-service communication
- [ ] Volume mounted for persistent SQLite database at `/data/db`
- [ ] `.env.example` file documents all environment variables
- [ ] `.env` file provides default development configuration
- [ ] `backend/Dockerfile` optimized for production use
- [ ] `frontend/Dockerfile` uses multi-stage build with Nginx
- [ ] Makefile or shell scripts provide dev, stop, restart commands
- [ ] `data/.gitignore` excludes database from version control
- [ ] `.dockerignore` files exist for both frontend and backend
- [ ] Project root `.gitignore` excludes env files and build artifacts
- [ ] README.md documents docker setup with quick start guide
## Technical Details
### docker-compose.yml (Project Root)
```yaml
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "8000:8000"
volumes:
- ./data/db:/app/data/db
environment:
- DATABASE_URL=sqlite:///./data/db/newzy.db
- DEBUG=false
- BACKEND_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
depends_on:
backend-db:
condition: service_healthy
networks:
- newzy-network
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "3000:80"
depends_on:
- backend
networks:
- newzy-network
restart: unless-stopped
networks:
newzy-network:
driver: bridge
ipam:
config:
- subnet: 172.28.0.0/16
volumes:
db-data:
name: newzy-db-data
```
### Environment Variables (.env.example)
| Variable | Description | Default | Required |
|----------|-------------|---------|----------|
| DATABASE_URL | SQLite database path | sqlite:///./data/db/newzy.db | Yes |
| DEBUG | Debug mode flag | false | No |
| BACKEND_CORS_ORIGINS | Allowed frontend origins | http://localhost:3000 | No |
| FRONTEND_API_URL | Backend API base URL | /api | No |
### Development Commands (Makefile)
```makefile
.PHONY: dev stop restart test clean build
dev:
docker compose up -d --build backend frontend
stop:
docker compose down
restart:
docker compose down
docker compose up -d --build backend frontend
test:
@echo "Running frontend tests..."
npm run test
@echo "Running backend tests..."
docker exec frontend npm run test || \
docker exec backend pytest
clean:
docker compose down -v
rm -rf data/
docker images | grep -E "(newzy|python|node)" | awk '{print $$3}' | xargs docker rmi
build:
docker compose build --no-cache
logs:
docker compose logs -f backend frontend
shell-backend:
docker exec -it backend bash
shell-frontend:
docker exec -it frontend sh
```
### Directory Structure with Docker Setup
```
newzy/
├── data/ # Local SQLite data directory
│ └── db/
│ └── newzy.db # Persisted database (excluded from git)
├── backend/
│ ├── Dockerfile
│ ├── requirements.txt
│ ├── .gitignore
│ └── pytest.ini
├── frontend/
│ ├── Dockerfile
│ ├── docker-compose.yml # Frontend-specific override (optional)
│ └── package.json
├── docker-compose.yml # Main orchestration file
├── .env # Development environment variables
├── .env.example # Template for .env
├── Makefile # Development shortcuts
├── .dockerignore # Exclude files from build context
└── data/.gitignore # Exclude database from git
```
### Multi-stage Build Strategy
**Backend Dockerfile:**
- Base: `python:3.11-slim`
- Install dependencies with `pip install --no-cache-dir`
- Copy only production code and requirements
- Expose port 8000
**Frontend Dockerfile:**
- Stage 1: `node:20-alpine` → Build frontend with Vite
- Stage 2: `nginx:alpine` → Serve built static files
- Nginx config routes all requests to index.html for SPA
### Service Communication Flow
```
Browser (localhost:3000)
↓ HTTP Request
Frontend Container (newzy-network:80)
↓ Forwarded to /api
Backend Container (newzy-network:8000)
↓ Connects to SQLite
Volume: data/db/newzy.db
```
## QA Notes
### Testing Checklist
- [ ] `docker compose up` starts both services without errors
- [ ] Frontend accessible at http://localhost:3000
- [ ] Backend accessible at http://localhost:8000
- [ ] Health endpoints respond correctly
- [ ] Database persists across service restarts
- [ ] `.env.example` contains all documented variables
- [ ] Makefile commands work (dev, stop, restart, clean)
- [ ] `data/` directory excluded from git commits
- [ ] `.gitignore` excludes environment files
### Security Considerations
- Never commit `.env` file to version control
- Use `.env.example` as template for new developers
- SQLite database stored locally, not in container (volume mounted)
- CORS configured with specific origins
- No production secrets exposed by default
### Performance Notes
- `--build` flag only when needed (avoid rebuilds on dev)
- Docker cache leveraged for incremental builds
- SQLite file storage faster than network databases for development
- Nginx serves static files efficiently in production
### Known Limitations
- Requires Docker Desktop or equivalent installed locally
- Mac users need sufficient disk space (~50GB recommended)
- Windows WSL2 required for best performance
- No GPU acceleration (CPU-based only)
- Production databases should use PostgreSQL, not SQLite
### Success Metrics
- `docker compose up` completes in under 5 minutes on first run
- Services restart within 10 seconds subsequent runs
- Development environment identical to staging/production setup
- Zero manual configuration required for new developers
- Makefile shortcuts reduce repetitive Docker commands