delpoyment with fully dockerized project on wixur.ir, dyolink docker hub created beside backend and frontend image is uploaded.

This commit is contained in:
2026-07-07 15:32:25 +03:30
parent e00af9f5be
commit 329d3f122c
28 changed files with 877 additions and 44 deletions

1
.gitignore vendored
View File

@@ -32,6 +32,7 @@ Thumbs.db
# === Docker ===
docker-compose.override.yml
infrastructure/nginx/generated/
*.log
docker-data/
postgres-data/

View File

@@ -6,6 +6,40 @@ Local development: see **`backend/README.md`** and **`frontend/README.md`**.
---
## Production deploy (Docker Hub + HTTPS + Let's Encrypt)
**Full step-by-step guide:** [`infrastructure/DEPLOY.md`](infrastructure/DEPLOY.md)
Minimal server setup: install Docker, create `.env` + `secrets/`, `docker login`, run one script.
| On server (once) | In repo / Docker |
|------------------|------------------|
| DNS A record → server IP | `docker-compose.prod.yml`, nginx, certbot |
| `docker login` (private Hub) | Build & push images from dev machine |
| `secrets/database.env`, `secrets/backend.env` | Examples: `database.prod.env.example`, `backend.prod.env.example` |
| `infrastructure/.env` (`DOMAIN`, `LETSENCRYPT_EMAIL`) | `deploy.prod.env.example` |
**Dev machine** — build frontend with the public domain baked in, push to Docker Hub:
```bash
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
```
**Server** — from `infrastructure/`:
```bash
cp deploy.prod.env.example .env # edit DOMAIN, paths
mkdir -p ../secrets && cp database.prod.env.example ../secrets/database.env
cp backend.prod.env.example ../secrets/backend.env # set passwords + FRONTEND_URL
docker login
chmod +x scripts/*.sh
./scripts/deploy-prod.sh
```
SSL is issued automatically via **Certbot** (`scripts/init-letsencrypt.sh`). Nginx config is generated from `DOMAIN` in `.env`. When you move to another domain (e.g. `dyolink.com`), update `.env` + `backend.env`, re-run `init-letsencrypt.sh`, and **rebuild the frontend image** with the new URL.
---
## Deploy on your own server (Docker + Gitea)
High level: **build container images → push to a registry → server pulls images and runs Compose**. Optionally **Gitea Actions** automates that on every merge to `main` / `master`.

View File

@@ -41,6 +41,6 @@ SMTP_USER=your_email@gmail.com
SMTP_PASSWORD=your_app_password
# SMS (sms.ir — use Sandbox API key for development)
# SMS_IR_API_KEY=lwbK7hxmjimNjFS4g5DWahh75EKCgJUfcUIinUQzfQXwXkSp
SMS_IR_API_KEY=4QKMiSU4Kh7tWPLCdRMV0QpDh8WgF33YkWRS18BcG3vf4QHi
# SMS_IR_API_KEY=4QKMiSU4Kh7tWPLCdRMV0QpDh8WgF33YkWRS18BcG3vf4QHi
SMS_IR_API_KEY=lwbK7hxmjimNjFS4g5DWahh75EKCgJUfcUIinUQzfQXwXkSp
SMS_IR_TEMPLATE_ID=123456

5
backend/.gitignore vendored
View File

@@ -3,6 +3,11 @@
/node_modules
/build
# Accidental tsc output next to Prisma sources (keep only .ts / schema / migrations)
/prisma/*.js
/prisma/*.d.ts
/prisma/*.js.map
# Logs
logs
*.log

View File

@@ -52,4 +52,4 @@ HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
ENTRYPOINT ["dumb-init", "--", "docker-entrypoint.sh"]
CMD ["node", "dist/main"]
CMD ["node", "dist/src/main.js"]

View File

@@ -9,6 +9,13 @@ if [ "$NODE_ENV" = "production" ]; then
echo "Running in PRODUCTION mode"
echo "Running database migrations..."
./node_modules/.bin/prisma migrate deploy
if [ -f "dist/prisma/seed.js" ]; then
echo "Seeding reference data (plans, org types, permissions)..."
node dist/prisma/seed.js
elif [ -f "prisma/seed.ts" ] || [ -f "prisma/seed.js" ]; then
echo "Running database seed..."
./node_modules/.bin/prisma db seed
fi
else
echo "Running in DEVELOPMENT mode"
echo "Syncing database schema..."

View File

@@ -11,7 +11,7 @@
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"start:prod": "node dist/src/main.js",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",

View File

@@ -3,16 +3,15 @@ import { PrismaClient } from '@prisma/client';
import { config } from 'dotenv';
import path from 'path';
// Load environment variables from the correct path
const envPath = path.join(__dirname, '..', '.env');
console.log('Loading .env from:', envPath);
config({ path: envPath });
// Load .env when running locally; Docker injects DATABASE_URL via env_file.
if (!process.env.DATABASE_URL) {
const envPath = path.join(__dirname, '..', '.env');
console.log('Loading .env from:', envPath);
config({ path: envPath });
}
// Verify DATABASE_URL is loaded
if (!process.env.DATABASE_URL) {
console.error('❌ DATABASE_URL is not set in environment');
console.log('Current directory:', process.cwd());
console.log('.env path:', envPath);
process.exit(1);
}

File diff suppressed because one or more lines are too long

View File

@@ -12,6 +12,7 @@
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2023",
"jsx": "react",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",

View File

@@ -19,6 +19,8 @@ DOMAIN=dyolink.com
# JWT_REFRESH_SECRET=another_long_random_secret_different_from_JWT_SECRET
# JWT_REFRESH_EXPIRES_IN=30d
# FRONTEND_URL=https://dyolink.com
# SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
# SMS_IR_TEMPLATE_ID=123456
# Frontend Environment (create frontend.env from this)
# NEXT_PUBLIC_API_URL=/api

421
infrastructure/DEPLOY.md Normal file
View File

@@ -0,0 +1,421 @@
# Dyolink — Production Server Deploy Guide
Deploy the full stack (Postgres, NestJS API, Next.js, Nginx, Let's Encrypt) on a fresh Linux server using **Docker Hub** images.
**Example used in production:** `https://wixur.ir` on server `185.243.48.140`.
---
## Architecture
```
Internet → Nginx (:80 / :443)
├── / → frontend:3000 (Next.js)
└── /api → backend:3000 (NestJS)
└── postgres:5432
```
| Service | Image | Notes |
|-----------|------------------------------------|--------------------------------|
| postgres | `postgres:15-alpine` | Data in Docker volume |
| backend | `dyolink/dyolink-backend:latest` | Runs migrations + seed on start |
| frontend | `dyolink/dyolink-frontend:latest` | URLs baked in at **build time** |
| nginx | `nginx:alpine` | SSL termination + reverse proxy |
| certbot | `certbot/certbot` | Auto-renews certificates |
---
## Prerequisites
### On your Mac (build machine)
- Docker Desktop running
- Repo cloned
- Docker Hub account (`dyolink`) with images pushed
### On the server
- Ubuntu 24.04 (or similar)
- Root or sudo access
- **Domain** with DNS **A record** → server public IP
- Ports **22**, **80**, **443** open (UFW + cloud provider firewall)
---
## Part 1 — Build & push images (Mac)
Frontend URLs are **compiled into the image**. Always build with the real public domain:
```bash
cd /path/to/dyolink
docker login # only needed on Mac to push
./infrastructure/scripts/build-and-push-prod.sh YOUR_DOMAIN.com latest
```
Example:
```bash
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
```
This pushes:
- `dyolink/dyolink-backend:latest`
- `dyolink/dyolink-frontend:latest`
**When to rebuild:** domain changes, frontend env (`NEXT_PUBLIC_*`) changes, or new app release.
---
## Part 2 — Server bootstrap (once per server)
SSH as root:
```bash
ssh root@YOUR_SERVER_IP
```
### 2.1 Update system & create deploy user
```bash
apt update && apt upgrade -y
apt install -y curl git ufw fail2ban
adduser dyolink
usermod -aG sudo dyolink
# Optional: copy SSH keys from root
mkdir -p /home/dyolink/.ssh
cp /root/.ssh/authorized_keys /home/dyolink/.ssh/ 2>/dev/null || true
chown -R dyolink:dyolink /home/dyolink/.ssh
chmod 700 /home/dyolink/.ssh
```
### 2.2 Install Docker
If `curl -fsSL https://get.docker.com | sh` returns **403**, use Ubuntu packages:
```bash
apt update
apt install -y docker.io docker-compose-v2
systemctl enable --now docker
usermod -aG docker dyolink
```
Verify:
```bash
docker --version
docker compose version
```
### 2.3 Docker Hub login (if images are private)
```bash
docker login
```
Public images skip this step.
### 2.4 Firewall
```bash
ufw default deny incoming
ufw default allow outgoing
ufw allow OpenSSH
ufw allow 80/tcp
ufw allow 443/tcp
ufw --force enable
```
Also open **80** and **443** in your VPS provider's cloud firewall panel if one exists.
### 2.5 DNS
Before SSL, confirm DNS:
```bash
dig +short YOUR_DOMAIN.com
# Must return YOUR_SERVER_IP
```
---
## Part 3 — Copy infrastructure to server (Mac)
```bash
cd /path/to/dyolink
ssh dyolink@YOUR_SERVER_IP "sudo mkdir -p /opt/dyolink/secrets && sudo chown -R dyolink:dyolink /opt/dyolink"
scp -r infrastructure/docker-compose.prod.yml \
infrastructure/nginx \
infrastructure/scripts \
infrastructure/database \
infrastructure/deploy.prod.env.example \
infrastructure/backend.prod.env.example \
infrastructure/database.prod.env.example \
dyolink@YOUR_SERVER_IP:/opt/dyolink/infrastructure/
```
On the server:
```bash
ssh dyolink@YOUR_SERVER_IP
chmod +x /opt/dyolink/infrastructure/scripts/*.sh
```
---
## Part 4 — Configure secrets (server)
### 4.1 Main `.env`
```bash
cd /opt/dyolink/infrastructure
cp deploy.prod.env.example .env
nano .env
```
```env
DOMAIN=wixur.ir
DOCKER_USERNAME=dyolink
TAG=latest
LETSENCRYPT_EMAIL=your-email@example.com
DEPLOY_SECRETS_DIR=/opt/dyolink/secrets
```
### 4.2 Database secrets
```bash
cp database.prod.env.example /opt/dyolink/secrets/database.env
nano /opt/dyolink/secrets/database.env
```
```env
POSTGRES_USER=dyolink_user
POSTGRES_PASSWORD=STRONG_PASSWORD_HERE
POSTGRES_DB=dyolink_db
```
### 4.3 Backend secrets
```bash
cp backend.prod.env.example /opt/dyolink/secrets/backend.env
nano /opt/dyolink/secrets/backend.env
```
Generate JWT secrets:
```bash
openssl rand -hex 32 # use for JWT_SECRET
openssl rand -hex 32 # use for JWT_REFRESH_SECRET (must be different)
```
```env
NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://dyolink_user:STRONG_PASSWORD_HERE@postgres:5432/dyolink_db
JWT_SECRET=<first openssl output>
JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=<second openssl output>
JWT_REFRESH_EXPIRES_IN=30d
FRONTEND_URL=https://wixur.ir
SMS_IR_API_KEY=your_key
SMS_IR_TEMPLATE_ID=your_template_id
```
**Critical checks:**
| Rule | Why |
|------|-----|
| `DATABASE_URL` password = `POSTGRES_PASSWORD` | Backend cannot connect otherwise |
| `FRONTEND_URL` = `https://YOUR_DOMAIN` | CORS, cookies, invite links |
| JWT secrets must **not** contain `CHANGE_ME` | App refuses to start (by design) |
| Postgres password set **before first** `up` | Password only applied on first volume create |
---
## Part 5 — Deploy (server)
```bash
cd /opt/dyolink/infrastructure
./scripts/deploy-prod.sh
```
This script:
1. Issues Let's Encrypt certificate (first run)
2. Renders HTTPS nginx config
3. Pulls images from Docker Hub
4. Starts all containers
First deploy takes **35 minutes**.
---
## Part 6 — Verify
```bash
docker compose -f docker-compose.prod.yml --env-file .env ps
```
Expected:
| Container | Status |
|-----------|--------|
| dyolink_db_prod | Up (healthy) |
| dyolink_backend_prod | Up (healthy) |
| dyolink_frontend_prod | Up |
| dyolink_nginx_prod | Up |
| dyolink_certbot_prod | Up |
```bash
curl -s https://YOUR_DOMAIN/api/health
# {"status":"ok","timestamp":"..."}
curl -I https://YOUR_DOMAIN/
# HTTP/2 200
```
Open `https://YOUR_DOMAIN` in a browser.
---
## Updating the app (new release)
**On Mac** — build & push:
```bash
./infrastructure/scripts/build-and-push-prod.sh wixur.ir latest
```
**On server:**
```bash
cd /opt/dyolink/infrastructure
docker compose -f docker-compose.prod.yml --env-file .env pull backend frontend
docker compose -f docker-compose.prod.yml --env-file .env up -d
```
Backend runs `prisma migrate deploy` automatically on container start.
---
## Troubleshooting
### Docker install: `get.docker.com` returns 403
Use `apt install docker.io docker-compose-v2` (see Part 2.2).
### Docker Hub pull: 403 Forbidden
```bash
docker login
```
If still blocked, transfer images from Mac:
```bash
# Mac
docker save dyolink/dyolink-backend:latest dyolink/dyolink-frontend:latest \
postgres:15-alpine nginx:alpine certbot/certbot:latest | gzip > images.tar.gz
scp images.tar.gz dyolink@SERVER:/tmp/
# Server
gunzip -c /tmp/images.tar.gz | docker load
```
### Backend crash: `JWT_SECRET must be changed from the placeholder value`
Edit `/opt/dyolink/secrets/backend.env` — replace JWT secrets with `openssl rand -hex 32` output. Restart:
```bash
docker compose -f docker-compose.prod.yml --env-file .env up -d backend
```
### HTTP shows "obtaining SSL certificate" / HTTPS fails
Nginx is still on the bootstrap config. Fix:
```bash
cd /opt/dyolink/infrastructure
./scripts/render-nginx-ssl.sh
docker compose -f docker-compose.prod.yml --env-file .env up -d nginx --force-recreate
curl -s https://YOUR_DOMAIN/api/health
```
### Backend `Restarting` — database password mismatch
If you changed `POSTGRES_PASSWORD` after the first deploy, reset the DB volume (destroys data):
```bash
docker compose -f docker-compose.prod.yml --env-file .env down
docker volume rm dyolink_postgres_data_prod
# Fix database.env + backend.env passwords to match
./scripts/deploy-prod.sh
```
### View logs
```bash
docker compose -f docker-compose.prod.yml --env-file .env logs backend --tail 50
docker compose -f docker-compose.prod.yml --env-file .env logs nginx --tail 50
docker compose -f docker-compose.prod.yml --env-file .env logs frontend --tail 50
```
### Internal health checks (bypass public network)
```bash
docker compose -f docker-compose.prod.yml --env-file .env exec nginx \
wget -qO- http://backend:3000/api/health
docker compose -f docker-compose.prod.yml --env-file .env exec frontend \
wget -qO- http://127.0.0.1:3000/ | head -3
```
---
## File reference
| Path on server | Purpose |
|----------------|---------|
| `/opt/dyolink/infrastructure/.env` | Domain, Docker Hub user, Let's Encrypt email |
| `/opt/dyolink/secrets/database.env` | Postgres credentials |
| `/opt/dyolink/secrets/backend.env` | API secrets, DATABASE_URL, JWT, SMS |
| `/opt/dyolink/infrastructure/nginx/generated/default.conf` | Auto-generated nginx SSL config |
| `/opt/dyolink/infrastructure/scripts/deploy-prod.sh` | Main deploy entry point |
| `/opt/dyolink/infrastructure/scripts/build-and-push-prod.sh` | Build & push (run on Mac) |
---
## Quick checklist (new server)
- [ ] DNS A record → server IP
- [ ] Docker installed on server
- [ ] UFW + cloud firewall: 22, 80, 443 open
- [ ] Images built with correct domain and pushed to Docker Hub
- [ ] `infrastructure/` copied to `/opt/dyolink/`
- [ ] `.env`, `database.env`, `backend.env` configured (real passwords + JWT)
- [ ] `./scripts/deploy-prod.sh` completed
- [ ] `curl https://DOMAIN/api/health` returns `{"status":"ok",...}`
- [ ] App loads in browser
---
## Issues encountered on first deploy (wixur.ir) — summary
| Problem | Cause | Type |
|---------|-------|------|
| `get.docker.com` 403 | Regional/network block | **Server setup** — use `apt install docker.io` |
| Docker Hub pull 403 | Hub blocked without login | **Server setup**`docker login` |
| Backend crash loop | `JWT_SECRET` still had `CHANGE_ME` | **Config** — edit `backend.env` |
| HTTP "obtaining SSL" / HTTPS broken | Nginx not recreated after SSL config | **Deploy script** — fixed in `init-letsencrypt.sh` / `deploy-prod.sh` |
| Frontend "unhealthy" in `docker ps` | Healthcheck timing; app still served pages | **Cosmetic** — no action needed |
**No application code changes were required.** The app, migrations, and seed all worked on first deploy once config was correct.

View File

@@ -0,0 +1,19 @@
# Copy to secrets/backend.env on the server.
# DATABASE_URL must match database.env credentials (host = postgres service name).
NODE_ENV=production
PORT=3000
DATABASE_URL=postgresql://dyolink_user:CHANGE_ME_STRONG_DB_PASSWORD@postgres:5432/dyolink_db
# Must be real random strings (openssl rand -hex 32). Values containing CHANGE_ME will crash the app.
JWT_SECRET=replace_with_openssl_rand_hex_32_output
JWT_EXPIRES_IN=15m
JWT_REFRESH_SECRET=replace_with_a_different_openssl_rand_hex_32_output
JWT_REFRESH_EXPIRES_IN=30d
# Must match DOMAIN in .env — used for CORS, invite links, cookies
FRONTEND_URL=https://wixur.ir
# SMS (sms.ir)
SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
SMS_IR_TEMPLATE_ID=123456

View File

@@ -11,3 +11,7 @@ JWT_REFRESH_EXPIRES_IN=30d
# CORS, cookies, and invite links — must match how users open the app (nginx host port)
FRONTEND_URL=http://178.131.50.201:8088
# SMS (sms.ir)
SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY
SMS_IR_TEMPLATE_ID=123456

View File

@@ -0,0 +1,4 @@
# Copy to secrets/database.env on the server (never commit real passwords).
POSTGRES_USER=dyolink_user
POSTGRES_PASSWORD=CHANGE_ME_STRONG_DB_PASSWORD
POSTGRES_DB=dyolink_db

View File

@@ -0,0 +1,18 @@
# Copy to infrastructure/.env on the server (not committed).
# docker compose -f docker-compose.prod.yml --env-file .env ...
DOMAIN=wixur.ir
DOCKER_USERNAME=dyolink
TAG=latest
# Let's Encrypt — certificate issuance and renewal notices
LETSENCRYPT_EMAIL=rameen.naghdi@gmail.com
# Optional: extra hostnames on the same cert (space-separated), e.g. www.wixur.ir
# CERTBOT_EXTRA_DOMAINS=www.wixur.ir
# Optional: use Let's Encrypt staging while testing (avoids rate limits)
# LETSENCRYPT_STAGING=1
# Folder with database.env and backend.env (absolute path on server recommended)
DEPLOY_SECRETS_DIR=/opt/dyolink/secrets

View File

@@ -1,16 +1,24 @@
# Production stack — pull images from Docker Hub, HTTPS via Let's Encrypt (certbot).
#
# Server setup (minimal):
# 1. Copy deploy.prod.env.example → .env (DOMAIN, DOCKER_USERNAME, LETSENCRYPT_EMAIL)
# 2. Copy secrets/*.example → ../secrets/ (database.env, backend.env) — outside git
# 3. docker login (private Docker Hub images)
# 4. ./scripts/init-letsencrypt.sh (first time only)
# 5. docker compose -f docker-compose.prod.yml --env-file .env up -d
#
# Updates: docker compose pull && docker compose up -d
name: dyolink-prod
services:
postgres:
image: postgres:15-alpine
container_name: dyolink_db_prod
env_file:
- database.env
- ${DEPLOY_SECRETS_DIR:-./secrets}/database.env
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DB:-dyolink_db}
- TZ=UTC
ports:
- "5433:5432"
TZ: UTC
volumes:
- postgres_data_prod:/var/lib/postgresql/data
- ./database/init.sql:/docker-entrypoint-initdb.d/init.sql:ro
@@ -19,12 +27,12 @@ services:
- dyolink_network
restart: unless-stopped
logging:
driver: "json-file"
driver: json-file
options:
max-size: "10m"
max-file: "3"
healthcheck:
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER}"]
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER"]
interval: 30s
timeout: 10s
retries: 3
@@ -37,18 +45,18 @@ services:
postgres:
condition: service_healthy
env_file:
- backend.env
- ${DEPLOY_SECRETS_DIR:-./secrets}/backend.env
environment:
- NODE_ENV=production
- TZ=UTC
- PORT=3000
ports:
- "4001:3000"
NODE_ENV: production
TZ: UTC
PORT: "3000"
expose:
- "3000"
networks:
- dyolink_network
restart: unless-stopped
logging:
driver: "json-file"
driver: json-file
options:
max-size: "10m"
max-file: "3"
@@ -57,26 +65,25 @@ services:
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
start_period: 60s
frontend:
image: ${DOCKER_USERNAME}/dyolink-frontend:${TAG:-latest}
container_name: dyolink_frontend_prod
depends_on:
- backend
env_file:
- frontend.env
environment:
- NODE_ENV=production
- TZ=UTC
- PORT=3000
ports:
- "4000:3000"
NODE_ENV: production
TZ: UTC
PORT: "3000"
HOSTNAME: "0.0.0.0"
expose:
- "3000"
networks:
- dyolink_network
restart: unless-stopped
logging:
driver: "json-file"
driver: json-file
options:
max-size: "10m"
max-file: "3"
@@ -85,34 +92,47 @@ services:
interval: 30s
timeout: 10s
retries: 3
start_period: 60s
nginx:
image: nginx:alpine
container_name: dyolink_nginx_prod
depends_on:
- backend
- frontend
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/conf.d/default.conf:ro
- ./ssl:/etc/nginx/ssl:ro
- ./nginx/generated/default.conf:/etc/nginx/conf.d/default.conf:ro
- certbot_conf:/etc/letsencrypt:ro
- certbot_www:/var/www/certbot:ro
- ./logs/nginx:/var/log/nginx
networks:
- dyolink_network
restart: unless-stopped
logging:
driver: "json-file"
driver: json-file
options:
max-size: "10m"
max-file: "3"
certbot:
image: certbot/certbot:latest
container_name: dyolink_certbot_prod
volumes:
- certbot_conf:/etc/letsencrypt
- certbot_www:/var/www/certbot
entrypoint: "/bin/sh -c 'trap exit TERM; while :; do certbot renew; sleep 12h & wait $${!}; done;'"
networks:
- dyolink_network
restart: unless-stopped
networks:
dyolink_network:
driver: bridge
name: dyolink_network
volumes:
postgres_data_prod:
name: dyolink_postgres_data_prod
certbot_conf:
name: dyolink_certbot_conf
certbot_www:
name: dyolink_certbot_www

View File

@@ -0,0 +1,17 @@
# Temporary HTTP-only config used while obtaining the first Let's Encrypt certificate.
# Replaced by nginx/generated/default.conf after ./scripts/init-letsencrypt.sh
server {
listen 80;
listen [::]:80;
server_name _;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 200 'Dyolink: obtaining SSL certificate. Retry shortly.';
add_header Content-Type text/plain;
}
}

View File

@@ -0,0 +1,97 @@
# Generated from nginx.ssl.conf.template — do not edit nginx/generated/default.conf by hand.
# Re-run: ./scripts/render-nginx-ssl.sh
upstream dyolink_backend {
server backend:3000;
keepalive 32;
}
upstream dyolink_frontend {
server frontend:3000;
keepalive 32;
}
server {
listen 80;
listen [::]:80;
server_name ${DOMAIN};
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name ${DOMAIN};
ssl_certificate /etc/letsencrypt/live/${DOMAIN}/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/${DOMAIN}/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;
client_max_body_size 50M;
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
location / {
proxy_pass http://dyolink_frontend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300;
proxy_connect_timeout 300;
}
location /api {
proxy_pass http://dyolink_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
proxy_read_timeout 300;
proxy_connect_timeout 300;
}
location /health {
access_log off;
return 200 "healthy\n";
add_header Content-Type text/plain;
}
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
}

0
infrastructure/scripts/backup.sh Normal file → Executable file
View File

View File

@@ -0,0 +1,48 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
INFRA_DIR="$SCRIPT_DIR/.."
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
DOMAIN="${1:-wixur.ir}"
TAG="${2:-latest}"
DOCKER_USERNAME="${DOCKER_USERNAME:-dyolink}"
PUBLIC_BASE="https://${DOMAIN}"
echo -e "${BLUE}Building Dyolink images for ${PUBLIC_BASE}${NC}"
echo -e "${YELLOW}Docker Hub: ${DOCKER_USERNAME}/dyolink-*:${TAG}${NC}"
if ! docker info >/dev/null 2>&1; then
echo "Docker is not running."
exit 1
fi
echo -e "${YELLOW}Ensure you are logged in: docker login${NC}"
docker build \
-t "${DOCKER_USERNAME}/dyolink-backend:${TAG}" \
-t "${DOCKER_USERNAME}/dyolink-backend:latest" \
"${REPO_ROOT}/backend"
docker build \
--build-arg "NEXT_PUBLIC_API_URL=${PUBLIC_BASE}/api" \
--build-arg "NEXT_PUBLIC_APP_URL=${PUBLIC_BASE}" \
--build-arg "NEXT_PUBLIC_APP_NAME=Dyolink" \
-t "${DOCKER_USERNAME}/dyolink-frontend:${TAG}" \
-t "${DOCKER_USERNAME}/dyolink-frontend:latest" \
"${REPO_ROOT}/frontend"
docker push "${DOCKER_USERNAME}/dyolink-backend:${TAG}"
docker push "${DOCKER_USERNAME}/dyolink-backend:latest"
docker push "${DOCKER_USERNAME}/dyolink-frontend:${TAG}"
docker push "${DOCKER_USERNAME}/dyolink-frontend:latest"
echo -e "${GREEN}Pushed:${NC}"
echo " ${DOCKER_USERNAME}/dyolink-backend:${TAG}"
echo " ${DOCKER_USERNAME}/dyolink-frontend:${TAG}"

2
infrastructure/scripts/build-and-push.sh Normal file → Executable file
View File

@@ -85,6 +85,8 @@ echo "JWT_SECRET=CHANGE_ME_32_CHARS_MINIMUM" >> $DEPLOY_DIR/backend.env.example
echo "DATABASE_URL=postgresql://\${POSTGRES_USER}:\${POSTGRES_PASSWORD}@postgres:5432/\${POSTGRES_DB}" >> $DEPLOY_DIR/backend.env.example
echo "CORS_ORIGIN=https://dyolink.com" >> $DEPLOY_DIR/backend.env.example
echo "FRONTEND_URL=https://dyolink.com" >> $DEPLOY_DIR/backend.env.example
echo "SMS_IR_API_KEY=CHANGE_ME_SMS_IR_API_KEY" >> $DEPLOY_DIR/backend.env.example
echo "SMS_IR_TEMPLATE_ID=123456" >> $DEPLOY_DIR/backend.env.example
echo "# Frontend" > $DEPLOY_DIR/frontend.env.example
echo "NEXT_PUBLIC_API_URL=/api" >> $DEPLOY_DIR/frontend.env.example

View File

@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INFRA_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$INFRA_DIR"
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'
echo -e "${BLUE}╔════════════════════════════════════════╗${NC}"
echo -e "${BLUE}║ Dyolink — Production Deploy ║${NC}"
echo -e "${BLUE}╚════════════════════════════════════════╝${NC}"
if [ ! -f .env ]; then
echo -e "${RED}Missing .env — copy deploy.prod.env.example to .env${NC}"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
SECRETS_DIR="${DEPLOY_SECRETS_DIR:-./secrets}"
if [ ! -f "${SECRETS_DIR}/database.env" ] || [ ! -f "${SECRETS_DIR}/backend.env" ]; then
echo -e "${RED}Missing secrets in ${SECRETS_DIR}/${NC}"
echo " Need: database.env and backend.env"
echo " Copy from database.prod.env.example and backend.prod.env.example"
exit 1
fi
COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)
if ! docker volume inspect dyolink_certbot_conf >/dev/null 2>&1 || \
! docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem" 2>/dev/null; then
echo -e "${YELLOW}No SSL certificate yet — running init-letsencrypt.sh first...${NC}"
./scripts/init-letsencrypt.sh
else
./scripts/render-nginx-ssl.sh
echo -e "${YELLOW}Pulling images...${NC}"
"${COMPOSE[@]}" pull backend frontend
echo -e "${YELLOW}Starting stack...${NC}"
"${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d
fi
sleep 8
echo -e "\n${GREEN}=== Status ===${NC}"
"${COMPOSE[@]}" ps
echo -e "\n${BLUE}App URL: https://${DOMAIN}${NC}"
echo -e "${BLUE}API health: https://${DOMAIN}/api/health${NC}"

0
infrastructure/scripts/deploy.sh Normal file → Executable file
View File

View File

@@ -0,0 +1,76 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
INFRA_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$INFRA_DIR"
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'
if [ ! -f .env ]; then
echo -e "${RED}Missing .env — copy deploy.prod.env.example to .env${NC}"
exit 1
fi
set -a
# shellcheck disable=SC1091
source .env
set +a
: "${DOMAIN:?Set DOMAIN in .env}"
: "${LETSENCRYPT_EMAIL:?Set LETSENCRYPT_EMAIL in .env}"
COMPOSE=(docker compose -f docker-compose.prod.yml --env-file .env)
mkdir -p nginx/generated logs/nginx database/backups
CERT_PATH="certbot_conf/live/${DOMAIN}/fullchain.pem"
if docker volume inspect dyolink_certbot_conf >/dev/null 2>&1; then
if docker run --rm -v dyolink_certbot_conf:/etc/letsencrypt:ro alpine \
test -f "/etc/letsencrypt/live/${DOMAIN}/fullchain.pem"; then
echo -e "${GREEN}Certificate already exists for ${DOMAIN}${NC}"
./scripts/render-nginx-ssl.sh
"${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d
exit 0
fi
fi
echo -e "${YELLOW}Phase 1: bootstrap nginx (HTTP) for ACME challenge...${NC}"
cp nginx/nginx.bootstrap.conf nginx/generated/default.conf
"${COMPOSE[@]}" up -d nginx
echo -e "${YELLOW}Phase 2: request Let's Encrypt certificate...${NC}"
CERTBOT_ARGS=(
certonly
--webroot
-w /var/www/certbot
--email "$LETSENCRYPT_EMAIL"
--agree-tos
--no-eff-email
-d "$DOMAIN"
)
if [ -n "${CERTBOT_EXTRA_DOMAINS:-}" ]; then
for extra in $CERTBOT_EXTRA_DOMAINS; do
CERTBOT_ARGS+=(-d "$extra")
done
fi
if [ "${LETSENCRYPT_STAGING:-0}" = "1" ]; then
CERTBOT_ARGS+=(--staging)
echo -e "${YELLOW}Using Let's Encrypt staging (test) certificates${NC}"
fi
"${COMPOSE[@]}" run --rm --entrypoint certbot certbot "${CERTBOT_ARGS[@]}"
echo -e "${YELLOW}Phase 3: enable HTTPS nginx config...${NC}"
./scripts/render-nginx-ssl.sh
"${COMPOSE[@]}" up -d --force-recreate nginx
"${COMPOSE[@]}" up -d
echo -e "${GREEN}SSL ready for https://${DOMAIN}${NC}"
echo -e "${GREEN}Certbot renewal container is running (checks every 12h).${NC}"

0
infrastructure/scripts/logs.sh Normal file → Executable file
View File

0
infrastructure/scripts/manage.sh Normal file → Executable file
View File

0
infrastructure/scripts/monitor.sh Normal file → Executable file
View File