fix(backend): P2 config & Docker consistency
Some checks failed
Lint and Build / format (pull_request) Successful in 1m44s
Lint and Build / clippy (pull_request) Successful in 1m48s
Lint and Build / build (pull_request) Successful in 6m40s
Lint and Build / test (pull_request) Failing after 1s

Resolve the operational/config sprawl (#10-#14 from the review): the app read
NORMOGEN_*/MONGODB_* env vars but every env/compose file set SERVER_*/DATABASE_*,
the ports were all over the place (8080/8000/6500/6800), there were 5
inconsistent Dockerfiles (rust:1.82 vs rust:1.93, missing curl), and an 18 MB
binary was committed.

Env-var names — standardize on what the code reads:
* config/mod.rs: NORMOGEN_PORT default 8080 -> 6500 (avoid the over-common
  8000/8080).
* db/mod.rs: create_database() now reads MONGODB_DATABASE (was DATABASE_NAME).
* .env.example, defaults.env, docker-compose.yml, docker-compose.dev.yml,
  DEPLOYMENT_GUIDE.md, deployment/README.md, deploy-and-test-solaria.sh,
  deploy-local-build.sh: use NORMOGEN_HOST/NORMOGEN_PORT/MONGODB_URI/
  MONGODB_DATABASE/APP_ENVIRONMENT; drop the dead SERVER_*/DATABASE_URI/
  DATABASE_NAME names.

Ports — canonical container port 6500 everywhere:
* Both Dockerfiles EXPOSE 6500; prod compose maps 6500:6500, dev 6501:6500.
* Bulk-replaced the long tail of solaria:8000/localhost:8000/localhost:8080 in
  docs and test scripts -> 6500.

Dockerfiles — 2 canonical, rust:latest, curl + healthcheck:
* backend/Dockerfile (prod): rust:latest builder, debian runtime now installs
  curl (so the compose HEALTHCHECK actually works), EXPOSE 6500.
* backend/docker/Dockerfile.dev (dev): rust:latest both stages, EXPOSE 6500.
* Deleted 3 redundant Dockerfiles (Dockerfile.improved x2, docker/Dockerfile).
* Deleted the committed 18 MB binary backend/docker/normogen-backend.
* Deleted 2 stray fix-notes in backend/docker/.

Compose:
* docker-compose.yml: correct env names, 6500:6500, APP_ENVIRONMENT=production,
  JWT_SECRET/ENCRYPTION_KEY required via compose interpolation, dropped the
  obsolete top-level version: key.
* docker-compose.dev.yml: correct env names, 6501:6500, mongo:7 (was 6.0),
  added a working backend healthcheck.
* Deleted docker/docker-compose.improved.yml + backend/deploy-to-solaria-improved.sh
  (built around the now-deleted 'improved' Docker files).

Verified: cargo fmt --check clean, build + clippy --all-targets clean, 18 unit
tests pass; grep confirms no SERVER_*/DATABASE_* env names and no rust:1.x tags
remain outside docs/archive and docs/adr (historical).
This commit is contained in:
goose 2026-06-27 19:54:32 -03:00
parent 17efc4f656
commit fff1ed2e6d
31 changed files with 115 additions and 553 deletions

View file

@ -6,8 +6,10 @@ RUST_LOG=info
# strong, non-default values.
APP_ENVIRONMENT=development
SERVER_HOST=0.0.0.0
SERVER_PORT=8000
# The app reads NORMOGEN_HOST / NORMOGEN_PORT (config/mod.rs), NOT SERVER_*.
# Defaults: host 0.0.0.0, port 6500.
NORMOGEN_HOST=0.0.0.0
NORMOGEN_PORT=6500
MONGODB_URI=mongodb://mongodb:27017
MONGODB_DATABASE=normogen
@ -15,6 +17,7 @@ MONGODB_DATABASE=normogen
# MUST be changed and MUST NOT equal "secret" when APP_ENVIRONMENT=production.
JWT_SECRET=change-this-to-a-strong-random-secret-key
JWT_ACCESS_TOKEN_EXPIRY_MINUTES=15
# Default is 7 days; 30 shown here as an opinionated example.
JWT_REFRESH_TOKEN_EXPIRY_DAYS=30
# MUST be set (and not the default) when APP_ENVIRONMENT=production.

View file

@ -1,43 +1,37 @@
# Use a lightweight Rust image
FROM rust:1.82-slim as builder
# Production image. Built by docker-compose.yml (`build: .`).
FROM rust:latest AS builder
WORKDIR /app
# Install build dependencies
# Build dependencies
RUN apt-get update && apt-get install -y \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy Cargo files
# Copy Cargo files and cache dependency build via a dummy main.rs
COPY Cargo.toml Cargo.lock ./
# Create a dummy main.rs to cache dependencies
RUN mkdir src && echo "fn main() {}" > src/main.rs
# Build dependencies
RUN cargo build --release && rm -rf src
# Copy actual source code
# Copy actual source and build the application
COPY src ./src
# Build the application
RUN touch src/main.rs && cargo build --release
# Runtime image
# --- runtime stage ---
FROM debian:bookworm-slim
# curl is required for the compose HEALTHCHECK to work.
RUN apt-get update && apt-get install -y \
ca-certificates \
libssl3 \
curl \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the binary from builder
COPY --from=builder /app/target/release/normogen-backend /app/normogen-backend
# Expose port
EXPOSE 8080
# The app listens on NORMOGEN_PORT (default 6500, set in compose/.env).
EXPOSE 6500
# Run the application
CMD ["./normogen-backend"]

View file

@ -1,55 +0,0 @@
# Multi-stage Dockerfile for Normogen Backend
# Stage 1: Build the Rust application
FROM rust:1.93-slim as builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy manifests
COPY Cargo.toml Cargo.lock ./
COPY src ./src
# Build the application in release mode
RUN cargo build --release
# Stage 2: Runtime image
FROM debian:bookworm-slim
# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
ca-certificates \
libssl3 \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean
# Create a non-root user
RUN useradd -m -u 1000 normogen
WORKDIR /app
# Copy the binary from builder
COPY --from=builder /app/target/release/normogen-backend /app/normogen-backend
# Change ownership
RUN chown -R normogen:normogen /app
# Switch to non-root user
USER normogen
# Expose the port
EXPOSE 8000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Set the entrypoint to ensure proper signal handling
ENTRYPOINT ["/app/normogen-backend"]
# Run with proper signal forwarding
CMD []

View file

@ -1,6 +1,6 @@
#!/bin/bash
API_URL="http://localhost:8080"
API_URL="http://localhost:6500"
USER_EMAIL="med-test-${RANDOM}@example.com"
USER_NAME="medtest${RANDOM}"

View file

@ -1 +0,0 @@
test

View file

@ -1,4 +1,4 @@
RUST_LOG=debug
SERVER_PORT=8000
NORMOGEN_PORT=6500
MONGODB_URI=mongodb://mongodb:27017
MONGODB_DATABASE=normogen

View file

@ -1,102 +0,0 @@
#!/bin/bash
set -e
echo "🚀 Deploying Normogen Backend to Solaria (Improved)"
echo "===================================================="
# Configuration
REMOTE_HOST="solaria"
REMOTE_DIR="/srv/normogen"
DOCKER_COMPOSE_FILE="docker/docker-compose.improved.yml"
# Colors for output
RED='\\033[0;31m'
GREEN='\\033[0;32m'
YELLOW='\\033[1;33m'
NC='\\033[0m' # No Color
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# Check if JWT_SECRET is set
if [ -z "${JWT_SECRET}" ]; then
log_error "JWT_SECRET environment variable not set!"
echo "Usage: JWT_SECRET=your-secret ./backend/deploy-to-solaria-improved.sh"
echo ""
echo "Generate a secure secret with:"
echo " openssl rand -base64 32"
exit 1
fi
# Step 1: Build locally
log_info "Step 1: Building backend binary locally..."
cargo build --release
log_info "✅ Build complete"
# Step 2: Create remote directory structure
log_info "Step 2: Setting up remote directory..."
ssh ${REMOTE_HOST} "mkdir -p ${REMOTE_DIR}/docker"
log_info "✅ Directory ready"
# Step 3: Create .env file on remote
log_info "Step 3: Setting up environment variables..."
ssh ${REMOTE_HOST} "cat > ${REMOTE_DIR}/.env << EOF
MONGODB_DATABASE=normogen
JWT_SECRET=${JWT_SECRET}
RUST_LOG=info
SERVER_PORT=8000
SERVER_HOST=0.0.0.0
EOF"
log_info "✅ Environment configured"
# Step 4: Copy improved Docker files to remote
log_info "Step 4: Copying Docker files to remote..."
scp docker/Dockerfile.improved ${REMOTE_HOST}:${REMOTE_DIR}/docker/Dockerfile.improved
scp docker/docker-compose.improved.yml ${REMOTE_HOST}:${REMOTE_DIR}/docker/docker-compose.improved.yml
log_info "✅ Docker files copied"
# Step 5: Stop old containers
log_info "Step 5: Stopping old containers..."
ssh ${REMOTE_HOST} "cd ${REMOTE_DIR} && docker compose down 2>/dev/null || true"
log_info "✅ Old containers stopped"
# Step 6: Start new containers with improved configuration
log_info "Step 6: Starting new containers..."
ssh ${REMOTE_HOST} "cd ${REMOTE_DIR} && docker compose -f ${DOCKER_COMPOSE_FILE} up -d"
log_info "✅ Containers started"
# Step 7: Wait for containers to be healthy
log_info "Step 7: Waiting for containers to stabilize..."
sleep 10
ssh ${REMOTE_HOST} "docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} ps"
log_info "✅ Container status retrieved"
# Step 8: Test API health endpoint
log_info "Step 8: Testing API health endpoint..."
sleep 5
if curl -f http://solaria.solivarez.com.ar:8001/health > /dev/null 2>&1; then
log_info "✅ API is responding correctly"
else
log_warn "⚠️ API health check failed - check logs with:"
echo " ssh ${REMOTE_HOST} 'docker logs -f normogen-backend'"
fi
log_info "🎉 Deployment complete!"
echo ""
echo "View logs:"
echo " ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} logs -f backend'"
echo ""
echo "View status:"
echo " ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} ps'"
echo ""
echo "Restart services:"
echo " ssh ${REMOTE_HOST} 'docker compose -f ${REMOTE_DIR}/${DOCKER_COMPOSE_FILE} restart'"

View file

@ -30,7 +30,7 @@ curl -s --max-time 3 http://localhost:6500/health || echo "Local connection fail
echo ""
echo "7. Testing container connection..."
docker exec normogen-backend-dev curl -s --max-time 3 http://localhost:8000/health || echo "Container connection failed"
docker exec normogen-backend-dev curl -s --max-time 3 http://localhost:6500/health || echo "Container connection failed"
echo ""
echo "=========================================="

View file

@ -8,27 +8,35 @@ services:
pull_policy: build
container_name: normogen-backend-dev
ports:
- '6500:8000'
# host 6501 (dev) -> container 6500, distinct from prod's 6500.
- '6501:6500'
volumes:
- ./src:/app/src
- startup-logs:/tmp
environment:
- APP_ENVIRONMENT=development
- RUST_LOG=debug
- SERVER_PORT=8000
- SERVER_HOST=0.0.0.0
- MONGODB_URI=mongodb://mongodb:27017
- DATABASE_NAME=normogen_dev
- JWT_SECRET=dev-jwt-secret-key-minimum-32-chars
- RUST_LOG_STYLE=always
- NORMOGEN_HOST=0.0.0.0
- NORMOGEN_PORT=6500
- MONGODB_URI=mongodb://mongodb:27017
- MONGODB_DATABASE=normogen_dev
- JWT_SECRET=dev-jwt-secret-key-minimum-32-chars
depends_on:
mongodb:
condition: service_healthy
networks:
- normogen-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:6500/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
restart: unless-stopped
mongodb:
image: mongo:6.0
image: mongo:7
container_name: normogen-mongodb-dev
ports:
- '27017:27017'

View file

@ -1,5 +1,3 @@
version: '3.8'
services:
mongodb:
image: mongo:7
@ -22,19 +20,23 @@ services:
container_name: normogen-backend
restart: unless-stopped
ports:
- "8000:8080"
- "6500:6500"
environment:
- DATABASE_URI=mongodb://mongodb:27017
- DATABASE_NAME=normogen
- JWT_SECRET=your-secret-key-change-in-production
- SERVER_HOST=0.0.0.0
- SERVER_PORT=8080
- RUST_LOG=debug
# The app reads NORMOGEN_* / MONGODB_* / APP_ENVIRONMENT (config/mod.rs).
- APP_ENVIRONMENT=production
- NORMOGEN_HOST=0.0.0.0
- NORMOGEN_PORT=6500
- MONGODB_URI=mongodb://mongodb:27017
- MONGODB_DATABASE=normogen
# Set real, strong values in your prod .env; production boot refuses insecure defaults.
- JWT_SECRET=${JWT_SECRET:?JWT_SECRET must be set}
- ENCRYPTION_KEY=${ENCRYPTION_KEY:?ENCRYPTION_KEY must be set}
- RUST_LOG=info
depends_on:
mongodb:
condition: service_healthy
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8080/health"]
test: ["CMD", "curl", "-f", "http://localhost:6500/health"]
interval: 30s
timeout: 10s
retries: 3

View file

@ -1,48 +0,0 @@
# Production Dockerfile (Multi-stage build)
# Stage 1: Build
FROM rust:1.93-slim AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy Cargo files first for better caching
COPY Cargo.toml ./
# Create dummy main.rs for dependency caching
RUN mkdir src && echo 'fn main() {}' > src/main.rs
# Build dependencies (this layer will be cached)
RUN cargo build --release && rm -rf src
# Copy actual source code
COPY src ./src
# Build the actual application
RUN cargo build --release
# Stage 2: Runtime
FROM debian:bookworm-slim
WORKDIR /app
# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
ca-certificates \
libssl3 \
&& rm -rf /var/lib/apt/lists/*
# Copy the binary from builder stage
COPY --from=builder /app/target/release/normogen-backend /app/normogen-backend
# Expose port
EXPOSE 8000
# Make the binary executable and run it
RUN chmod +x /app/normogen-backend
CMD ["/app/normogen-backend"]

View file

@ -1,40 +1,35 @@
# Development Dockerfile
# Uses Rust 1.93+ to support Edition 2024 dependencies
FROM rust:1.93-slim as builder
# Development image. Built by docker-compose.dev.yml.
# Debug build; the dev compose mounts ./src:/app/src for rapid rebuilds.
FROM rust:latest AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy Cargo files first for better caching
# Cache dependency build via a dummy main.rs
COPY Cargo.toml ./
# Create dummy main.rs for dependency caching
RUN mkdir src && echo 'fn main() {}' > src/main.rs
# Build dependencies (this layer will be cached)
RUN cargo build && rm -rf src
# Copy actual source code
# Copy actual source and build
COPY src ./src
# Build the application
RUN cargo build
# Runtime stage
FROM rust:1.93-slim
# Runtime stage — full Rust image so the dev compose can rebuild in-container.
# curl is required for the compose HEALTHCHECK to work.
FROM rust:latest
RUN apt-get update && apt-get install -y \
curl \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
# Copy the binary from builder
COPY --from=builder /app/target/debug/normogen-backend /app/normogen-backend
# Expose port
EXPOSE 8000
# The app listens on NORMOGEN_PORT (default 6500, set in compose/.env).
EXPOSE 6500
# Run the binary directly
CMD ["/app/normogen-backend"]

View file

@ -1,65 +0,0 @@
# Multi-stage build for smaller, more secure image
# Stage 1: Build
FROM rust:1.93-slim AS builder
WORKDIR /app
# Install build dependencies
RUN apt-get update && apt-get install -y \
pkg-config \
libssl-dev \
&& rm -rf /var/lib/apt/lists/*
# Copy manifests first (better layer caching)
COPY Cargo.toml Cargo.lock ./
# Create dummy main.rs to cache dependencies
RUN mkdir src && \
echo "fn main() {}" > src/main.rs && \
cargo build --release && \
rm -rf src
# Copy actual source
COPY src ./src
# Build application
RUN cargo build --release
# Stage 2: Runtime
FROM debian:bookworm-slim
# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
ca-certificates \
libssl3 \
curl \
&& rm -rf /var/lib/apt/lists/* \
&& apt-get clean
# Create non-root user
RUN useradd -m -u 1000 normogen && \
mkdir -p /app && \
chown -R normogen:normogen /app
WORKDIR /app
# Copy binary from builder
COPY --from=builder /app/target/release/normogen-backend /app/normogen-backend
# Set permissions
RUN chmod +x /app/normogen-backend && \
chown normogen:normogen /app/normogen-backend
# Switch to non-root user
USER normogen
# Expose port
EXPOSE 8000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
CMD curl -f http://localhost:8000/health || exit 1
# Run with proper signal handling
ENTRYPOINT ["/app/normogen-backend"]
CMD []

View file

@ -1,43 +0,0 @@
# Fix for Rust Edition 2024 Docker Build Error
## Problem
The error occurs because:
1. Your Dockerfile uses `FROM rust:latest` which pulled `rust:1.83-alpine`
2. Several dependencies require Rust 1.85+ for Edition 2024 support:
- `time-core 0.1.8` requires Rust 1.88.0
- `getrandom 0.4.1` requires Rust 1.85.0
- `uuid 1.21.0` requires Rust 1.85.0
- `deranged 0.5.6` requires Rust 1.85.0
- `wasip2/wasip3` require Rust 1.87.0
## Root Cause
Rust Edition 2024 became stable in Rust 1.85.0 (released February 20, 2025).
Some of your transitive dependencies have updated to use Edition 2024,
which requires a newer Rust version than 1.83.
## Solutions
### ✅ RECOMMENDED: Update Rust Base Image
Change `FROM rust:latest` to `FROM rust:1.93` or newer.
**Pros:**
- Future-proof solution
- Gets latest Rust improvements and security fixes
- No dependency management overhead
- Standard practice (update base images regularly)
**Cons:**
- None (this is the correct approach)
### Alternative: Pin Dependency Versions (NOT RECOMMENDED)
Pin problematic dependencies to older versions that don't require Edition 2024.
This creates technical debt and should only be used if you have a specific
constraint preventing Rust version updates.
## Implementation
See the fixed Dockerfiles in this directory.

View file

@ -1,60 +0,0 @@
# MongoDB Health Check Fix
## Problem
The MongoDB container was failing health checks with the original configuration:
```yaml
healthcheck:
test: ['CMD', 'mongosh', '--eval', 'db.adminCommand.ping()']
start_period: 10s # Too short!
```
## Root Causes
1. **start_period too short**: 10s isn't enough for MongoDB to initialize, especially on first start
2. **Command format**: The healthcheck needs proper output handling
## Solution
Updated healthcheck in docker-compose.dev.yml:
```yaml
healthcheck:
test: |
mongosh --eval "db.adminCommand('ping').ok" --quiet
interval: 10s
timeout: 5s
retries: 5
start_period: 40s # Increased from 10s to 40s
```
## Changes Made
- ✅ Increased `start_period` from 10s to 40s (gives MongoDB time to initialize)
- ✅ Simplified the healthcheck command to use shell format
- ✅ Added `--quiet` flag to suppress verbose output
## How to Apply
On your server:
```bash
# Pull the latest changes
git pull origin main
# Stop and remove existing containers
docker compose -f docker-compose.dev.yml down -v
# Start fresh
docker compose -f docker-compose.dev.yml up -d
# Watch the logs
docker compose -f docker-compose.dev.yml logs -f mongodb
```
## Verify Health Check
```bash
# Check container health
docker ps --format "table {{.Names}} {{.Status}}"
# Check health status specifically
docker inspect normogen-mongodb-dev --format='{{.State.Health.Status}}'
```
Expected output: `healthy`

View file

@ -1,68 +0,0 @@
version: '3.8'
services:
mongodb:
image: mongo:6.0
container_name: normogen-mongodb
restart: unless-stopped
ports:
- "27017:27017"
environment:
MONGO_INITDB_DATABASE: normogen
volumes:
- mongodb_data:/data/db
- mongodb_config:/data/configdb
networks:
- normogen-network
healthcheck:
test: ["CMD", "mongosh", "--eval", "db.adminCommand('ping')"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
backend:
build:
context: ..
dockerfile: docker/Dockerfile.improved
image: normogen-backend:latest
container_name: normogen-backend
restart: unless-stopped
ports:
- "8001:8000"
environment:
RUST_LOG: ${RUST_LOG:-info}
MONGODB_URI: mongodb://mongodb:27017
MONGODB_DATABASE: ${MONGODB_DATABASE:-normogen}
JWT_SECRET: ${JWT_SECRET}
SERVER_PORT: 8000
SERVER_HOST: 0.0.0.0
depends_on:
mongodb:
condition: service_healthy
networks:
- normogen-network
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 10s
deploy:
resources:
limits:
cpus: '1.0'
memory: 512M
reservations:
cpus: '0.25'
memory: 128M
volumes:
mongodb_data:
driver: local
mongodb_config:
driver: local
networks:
normogen-network:
driver: bridge

Binary file not shown.

View file

@ -147,7 +147,7 @@ impl Config {
server: ServerConfig {
host: std::env::var("NORMOGEN_HOST").unwrap_or_else(|_| "0.0.0.0".to_string()),
port: std::env::var("NORMOGEN_PORT")
.unwrap_or_else(|_| "8080".to_string())
.unwrap_or_else(|_| "6500".to_string())
.parse()?,
},
database: DatabaseConfig {

View file

@ -23,7 +23,7 @@ pub use mongodb_impl::MongoDb;
pub async fn create_database() -> Result<Database> {
let mongo_uri = env::var("MONGODB_URI").expect("MONGODB_URI must be set");
let db_name = env::var("DATABASE_NAME").expect("DATABASE_NAME must be set");
let db_name = env::var("MONGODB_DATABASE").expect("MONGODB_DATABASE must be set");
let client = Client::with_uri_str(&mongo_uri).await?;
let database = client.database(&db_name);

View file

@ -3,7 +3,7 @@
# Phase 2.8 Test Suite
# Tests Pill Identification, Drug Interactions, and Reminder System
API_URL="http://localhost:8080/api"
API_URL="http://localhost:6500/api"
TEST_USER="test_phase28@example.com"
TEST_PASSWORD="TestPassword123!"