Added deployment files

This commit is contained in:
Oleksandr Prokhorenko
2026-09-24 23:09:44 +03:00
parent 7f3a56a4ca
commit c345a8e91f
14 changed files with 402 additions and 5 deletions
+19
View File
@@ -0,0 +1,19 @@
.git
.env
.env.*
**/.env
**/.env.*
**/node_modules
**/dist
**/.turbo
.pnpm-store
packages/database/src/generated
playwright-report
test-results
coverage
**/*.tsbuildinfo
**/.DS_Store
*.log
deploy/*.env
deploy/state
deploy/backups
+1
View File
@@ -1,4 +1,5 @@
DATABASE_URL=postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow
API_PORT=3001
API_HOST=127.0.0.1
WEB_PORT=5173
APP_ORIGIN=http://localhost:5173
+40
View File
@@ -0,0 +1,40 @@
# syntax=docker/dockerfile:1
FROM node:22.19.0-bookworm-slim AS dependencies
WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends openssl ca-certificates \
&& rm -rf /var/lib/apt/lists/* \
&& npm install --global [email protected]
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY apps/api/package.json ./apps/api/package.json
COPY apps/web/package.json ./apps/web/package.json
COPY packages/contracts/package.json ./packages/contracts/package.json
COPY packages/database/package.json ./packages/database/package.json
COPY packages/ui/package.json ./packages/ui/package.json
RUN pnpm install --frozen-lockfile
FROM dependencies AS source
COPY . .
FROM source AS api-build
RUN pnpm exec turbo run build --filter=@merchantflow/api
# Retain the workspace dependency layout and Prisma CLI for one-off migrations.
# No production secrets are supplied during the build.
FROM dependencies AS api
COPY --from=api-build /app/apps/api/dist ./apps/api/dist
COPY --from=api-build /app/packages/contracts/dist ./packages/contracts/dist
COPY --from=api-build /app/packages/database/dist ./packages/database/dist
COPY --from=api-build /app/packages/database/prisma ./packages/database/prisma
COPY --from=api-build /app/packages/database/prisma.config.ts ./packages/database/prisma.config.ts
ENV NODE_ENV=production API_HOST=0.0.0.0 API_PORT=3001
USER node
EXPOSE 3001
CMD ["node", "apps/api/dist/main.js"]
FROM source AS web-build
RUN pnpm exec turbo run build --filter=@merchantflow/web
FROM nginx:1.28-alpine AS web
COPY deploy/web.conf /etc/nginx/conf.d/default.conf
COPY --from=web-build /app/apps/web/dist /usr/share/nginx/html
EXPOSE 80
+5 -2
View File
@@ -2,6 +2,9 @@
A local Merchant Onboarding CRM for a fictional crypto-payment provider. The workspace provides database-backed login, role-scoped reads and writes, commercial onboarding, Compliance reviews, and a responsive English/Russian UI.
For VPS production containers, see the [deployment guide](docs/deployment.md).
It covers Docker builds, environment setup, migrations, initial demo seeding, and updates.
## Start locally
Prerequisites: Node **22.19+ on the 22.x line**, pnpm **10.32.1**, and Docker Desktop with its engine running. `.nvmrc` pins the verified Node version.
@@ -136,7 +139,7 @@ curl --fail http://localhost:5173/api/health
Both should return `{"status":"ok","database":"connected"}`. If startup fails, check Docker, port availability and `.env`; do not point the tests at development data.
The [product brief](docs/product-brief.md) and [implementation checklist](docs/implementation-checklist.md) record the accepted scope and verification results. Merchant editing, ownership handoff, stage/review actions and task management are implemented. Uploads, merchant self-service, payments, external KYB/reminders and deployment remain out of scope.
The [product brief](docs/product-brief.md) and [implementation checklist](docs/implementation-checklist.md) record the accepted scope and verification results. Merchant editing, ownership handoff, stage/review actions and task management are implemented. Uploads, merchant self-service, payments and external KYB/reminders remain out of scope. Production container setup is documented in the [deployment guide](docs/deployment.md).
## Editing and workflow rules
@@ -159,7 +162,7 @@ All mutation bodies carry the merchant's current integer `version`. Transactions
| POST / PATCH | `/api/merchants/:id/activities[/:activityId]` | Commercial interactions or Compliance KYB notes |
| POST / PATCH | `/api/merchants/:id/tasks[/:taskId]` | Authorized task creation/editing/completion |
No staff registration, merchant deletion UI, file uploads, payments, external notifications, or deployment is included. Authentication credentials never enter localStorage; only the UI language does.
No staff registration, merchant deletion UI, file uploads, payments, or external notifications are included. Authentication credentials never enter localStorage; only the UI language does.
## Seed upgrade behavior
+1
View File
@@ -7,6 +7,7 @@ export const env = z
.url()
.default('postgresql://merchantflow:merchantflow_local@localhost:55440/merchantflow'),
API_PORT: z.coerce.number().default(3001),
API_HOST: z.string().min(1).default('127.0.0.1'),
APP_ORIGIN: z.url().default('http://localhost:5173'),
NODE_ENV: z.string().default('development'),
})
+2 -2
View File
@@ -1,5 +1,5 @@
import { createApp } from './app.js';
import { env } from './env.js';
const app = await createApp();
await app.listen(env.API_PORT, '127.0.0.1');
console.log(`MerchantFlow API: http://localhost:${env.API_PORT}/api/health`);
await app.listen(env.API_PORT, env.API_HOST);
console.log(`MerchantFlow API: http://${env.API_HOST}:${env.API_PORT}/api/health`);
+73
View File
@@ -0,0 +1,73 @@
name: merchantflow
x-logging: &logging
driver: json-file
options:
max-size: '10m'
max-file: '3'
services:
db:
image: postgres:17.6-alpine
restart: unless-stopped
environment:
POSTGRES_USER: merchantflow
POSTGRES_DB: merchantflow
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD in the production env file}
volumes:
- database:/var/lib/postgresql/data
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U merchantflow -d merchantflow']
interval: 5s
timeout: 5s
retries: 20
start_period: 10s
logging: *logging
api:
image: merchantflow-api:${APP_IMAGE_TAG:-local}
build:
context: .
target: api
restart: unless-stopped
init: true
environment:
NODE_ENV: production
API_HOST: 0.0.0.0
API_PORT: '3001'
APP_ORIGIN: ${APP_ORIGIN:?Set APP_ORIGIN in the production env file}
DATABASE_URL: ${DATABASE_URL:?Set DATABASE_URL in the production env file}
ports:
- '127.0.0.1:13001:3001'
depends_on:
db:
condition: service_healthy
healthcheck:
test:
- CMD
- node
- -e
- "fetch('http://127.0.0.1:3001/api/health', {signal: AbortSignal.timeout(4000)}).then(r => {if (!r.ok) process.exit(1)}).catch(() => process.exit(1))"
interval: 10s
timeout: 5s
retries: 12
start_period: 15s
logging: *logging
web:
image: merchantflow-web:${APP_IMAGE_TAG:-local}
build:
context: .
target: web
restart: unless-stopped
ports:
- '127.0.0.1:18080:80'
healthcheck:
test: ['CMD', 'wget', '-q', '-O', '/dev/null', 'http://127.0.0.1/healthz']
interval: 10s
timeout: 5s
retries: 6
logging: *logging
volumes:
database:
+12
View File
@@ -0,0 +1,12 @@
#!/usr/bin/env bash
set -euo pipefail
repo_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
env_file=${MERCHANTFLOW_ENV_FILE:-/opt/merchantflow/production.env}
if [[ ! -r "$env_file" ]]; then
echo "Missing production configuration: $env_file (run deploy/init-env.sh first)" >&2
exit 1
fi
# Use an explicit file so the local development .env is never loaded by Compose.
exec docker compose --project-name "${MERCHANTFLOW_PROJECT:-merchantflow}" \
--env-file "$env_file" -f "$repo_dir/compose.production.yaml" "$@"
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
env_file=${1:-/opt/merchantflow/production.env}
if [[ -e "$env_file" ]]; then
echo "Refusing to overwrite existing configuration: $env_file" >&2
exit 1
fi
command -v openssl >/dev/null
password=$(openssl rand -hex 32)
mkdir -p "$(dirname "$env_file")"
# noclobber also protects against a concurrent initialization.
set -o noclobber
cat > "$env_file" <<EOF
POSTGRES_PASSWORD=$password
DATABASE_URL=postgresql://merchantflow:$password@db:5432/merchantflow
APP_ORIGIN=https://merchantflow.prvt.you
NODE_ENV=production
API_HOST=0.0.0.0
API_PORT=3001
EOF
unset password
echo "Created $env_file with private permissions. Keep it outside Git."
+7
View File
@@ -0,0 +1,7 @@
# Reference only. Run init-env.sh to generate the actual file outside the repo.
POSTGRES_PASSWORD=replace-with-generated-hex-password
DATABASE_URL=postgresql://merchantflow:replace-with-generated-hex-password@db:5432/merchantflow
APP_ORIGIN=https://merchantflow.prvt.you
NODE_ENV=production
API_HOST=0.0.0.0
API_PORT=3001
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
seed_demo=false
if [[ $# -gt 1 || ( $# -eq 1 && $1 != --seed-demo ) ]]; then
echo "Usage: bash deploy/start.sh [--seed-demo]" >&2
exit 1
fi
if [[ ${1:-} == --seed-demo ]]; then seed_demo=true; fi
repo_dir=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
env_file=${MERCHANTFLOW_ENV_FILE:-/opt/merchantflow/production.env}
state_dir=$(dirname "$env_file")
compose() { bash "$repo_dir/deploy/compose.sh" "$@"; }
command -v flock >/dev/null || { echo 'Run this script on the Linux VPS (flock required).' >&2; exit 1; }
[[ -r "$env_file" ]] || { echo "Missing $env_file; run init-env.sh first." >&2; exit 1; }
exec 9>"$state_dir/deploy.lock"
flock -n 9 || { echo 'Another deployment is running.' >&2; exit 1; }
compose config --quiet
command -v ss >/dev/null || { echo 'Install iproute2 for the port availability check.' >&2; exit 1; }
for pair in api:13001 web:18080; do
service=${pair%:*}
port=${pair#*:}
if [[ -n $(ss -H -ltn "sport = :$port") && -z $(compose ps --status running -q "$service") ]]; then
echo "Port $port is already occupied by another service. Resolve this before deployment." >&2
exit 1
fi
done
# Build before touching running services. Migration/seed commands never publish API ports.
compose build api web
compose up -d --wait --wait-timeout 120 db
mkdir -p "$state_dir/backups"
backup="$state_dir/backups/$(date -u +%Y%m%dT%H%M%SZ).dump"
compose exec -T db pg_dump -U merchantflow -d merchantflow -Fc > "$backup.tmp"
mv "$backup.tmp" "$backup"
compose run --rm --no-deps api pnpm --filter @merchantflow/database migrate
if $seed_demo; then
user_count=$(compose exec -T db psql -U merchantflow -d merchantflow -Atc 'SELECT count(*) FROM "User"')
if [[ "$user_count" != 0 ]]; then
echo 'Database already has users. Rerun without --seed-demo; existing data was not reseeded.' >&2
exit 1
fi
compose run --rm --no-deps api node packages/database/dist/seed.js
fi
if ! compose up -d --wait --wait-timeout 180 api web; then
echo "Startup failed. Inspect: bash deploy/compose.sh logs --tail=100 api web" >&2
echo "Database backup: $backup. No database rollback was attempted." >&2
exit 1
fi
echo 'App containers are healthy. Host Nginx can use 127.0.0.1:18080 and 127.0.0.1:13001.'
echo "Pre-migration database backup: $backup"
+27
View File
@@ -0,0 +1,27 @@
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.html;
server_tokens off;
location = /healthz {
access_log off;
default_type text/plain;
return 200 "ok\n";
}
# Host Nginx routes API traffic directly to the API container.
location = /api { return 404; }
location ^~ /api/ { return 404; }
location /assets/ {
try_files $uri =404;
add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
try_files $uri $uri/ /index.html;
add_header Cache-Control "no-cache" always;
}
}
+135
View File
@@ -0,0 +1,135 @@
# Production containers on the VPS
This is deployment step 2: build and run the app behind the existing host Nginx.
The containers listen only on the VPS loopback interface. The public domain will
work after step 3 installs its certificate and host Nginx virtual host. Gitea
Actions automation is a separate step; these scripts also support manual deployment.
## Prerequisites
Use the Linux VPS with Docker Engine, Docker Compose v2 supporting `up --wait`,
Git, OpenSSL, `flock` (util-linux), and `ss` (iproute2). Run application commands
as a deployment user that can use Docker. Docker group membership grants
administrative access to the host. Node and pnpm are installed inside the images;
they are not required on the VPS.
Commit and push the new deployment files from the development machine before
cloning/pulling on the VPS. Use the existing Gitea repository credentials when
prompted; don't embed a token in a remote URL.
## First installation
Run these commands on the VPS as the intended deployment user. The `install`
command needs sudo and gives that user ownership of the application directory:
```bash
sudo install -d -m 750 -o "$(id -un)" -g "$(id -gn)" /opt/merchantflow
git clone https://git.prvt.you/gitadmin/test-assignment.git /opt/merchantflow/app
cd /opt/merchantflow/app
bash deploy/init-env.sh
bash deploy/start.sh --seed-demo
```
If already cloned, use the existing checkout and pull the committed deployment
changes instead of cloning again. The scripts locate the checkout themselves.
`init-env.sh` generates a random 64-character hexadecimal database password and
writes `/opt/merchantflow/production.env` with mode `600`. The same password is
used in `POSTGRES_PASSWORD` and `DATABASE_URL`. It refuses to overwrite an existing
file. Never commit this file or put it inside the source checkout. Hexadecimal
passwords need no URL escaping. `deploy/production.env.example` documents the
configuration without containing a real secret.
The API uses `NODE_ENV=production`, `API_HOST=0.0.0.0`, port `3001`, and
`APP_ORIGIN=https://merchantflow.prvt.you`. Production Compose fixes the first
three values; its origin and database credentials come from the explicit env
file. Local development retains the loopback API bind default. Do not export a
development `DATABASE_URL`, `APP_ORIGIN`, or `POSTGRES_PASSWORD` in the deployment
shell: shell variables take precedence over Compose's env file.
`start.sh` serializes deployments with a lock, checks host ports, builds both
images before changing services, waits for PostgreSQL, writes a `pg_dump -Fc`
backup, and applies checked-in migrations using `prisma migrate deploy`. The
explicit `--seed-demo` option then populates an empty user table with the demo
accounts and fictional records. It refuses to reseed an existing populated
database. API and frontend start only after these commands succeed.
There are no public PostgreSQL ports. The project has its own persistent
`merchantflow_database` volume, separate from the local development database.
Container logs rotate at 10 MB with three files per service. API runs as the
unprivileged Node user. Its image retains the workspace dependency layout and
Prisma CLI so migrations don't require installing tools at deployment time.
The web image contains only Nginx configuration and built static assets.
## Verify on the VPS
```bash
bash deploy/compose.sh ps
curl --fail http://127.0.0.1:13001/api/health
curl --fail -I http://127.0.0.1:18080/
curl --fail -I http://127.0.0.1:18080/login
```
All three containers should be healthy. The API health response is
`{"status":"ok","database":"connected"}`. Frontend routes return the SPA on
refresh. Hashed `/assets/` files get immutable caching; HTML requires
revalidation, and missing assets return 404. `/api` paths on the frontend
container deliberately return 404: host Nginx must forward those paths directly
to the API, preserving the `/api` prefix.
The next step's host Nginx upstreams are:
| Route | Upstream |
| ------------------- | ------------------------ |
| `/` | `http://127.0.0.1:18080` |
| `/api` and `/api/*` | `http://127.0.0.1:13001` |
Browser sign-in should be checked at the final HTTPS origin after step 3. The
current production origin check and secure session cookies intentionally don't
support signing in via plain HTTP on the loopback ports.
## Subsequent updates
```bash
cd /opt/merchantflow/app
git pull --ff-only origin main
bash deploy/start.sh
```
Omit `--seed-demo` on updates. Migrations run without resetting data or changing
existing demo credentials. Backups go to `/opt/merchantflow/backups`; copy these
off-server and manage retention separately. The script aborts on build, backup,
or migration failure. A failed container health check reports an error and
leaves logs available; this step does not implement automatic application or
database rollback. Brief downtime while containers restart is expected.
For commit-tagged images, set `APP_IMAGE_TAG` consistently on commands:
```bash
export APP_IMAGE_TAG=$(git rev-parse HEAD)
bash deploy/start.sh
```
The default image tag is `local`. The later Actions workflow can supply its
commit SHA instead. `MERCHANTFLOW_ENV_FILE` overrides the env-file path and
`MERCHANTFLOW_PROJECT` overrides the Compose project name, primarily for isolated
verification. Keep the production project name stable to reuse its database
volume. Host port mappings remain fixed.
## Operations
```bash
bash deploy/compose.sh logs --tail=100 api web db
bash deploy/compose.sh restart api web
bash deploy/compose.sh stop
bash deploy/compose.sh up -d --wait
```
Do not run `down -v`: that deletes the database volume. Changing
`POSTGRES_PASSWORD` in the env file does not rotate the password in an existing
PostgreSQL volume; a rotation must update the database role and `DATABASE_URL`
together. Do not use the development `pnpm db:setup` command on this server.
The Compose configuration waits for database readiness using a health check;
ordinary container startup order alone doesn't establish readiness.
[Docker startup-order documentation](https://docs.docker.com/compose/how-tos/startup-order/)
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://turbo.build/schema.json",
"globalDependencies": [".env", "tsconfig.base.json"],
"globalEnv": ["DATABASE_URL", "API_PORT", "WEB_PORT", "APP_ORIGIN", "NODE_ENV"],
"globalEnv": ["DATABASE_URL", "API_PORT", "API_HOST", "WEB_PORT", "APP_ORIGIN", "NODE_ENV"],
"tasks": {
"build": { "dependsOn": ["^build"], "outputs": ["dist/**"] },
"@merchantflow/ui#build": { "outputs": [] },