rivisto completamente il deploy
This commit is contained in:
8 files changed
+474
-80
No files matched your search
@@ -0,0 +1,14 @@
|
|||||||
|
# Copia questo file in ".env" e valorizza le variabili.
|
||||||
|
# Il file ".env" NON va committato (contiene segreti).
|
||||||
|
|
||||||
|
# Immagine dell'applicazione (usa un tag versionato o un digest, NON :latest)
|
||||||
|
# Esempio digest: registry.example.com/tuo-utente/blog@sha256:...
|
||||||
|
BLOG_IMAGE=registry.example.com/tuo-utente/blog:1.0.0
|
||||||
|
|
||||||
|
# Password del database PostgreSQL (usata sia da postgresql che dall'app blog)
|
||||||
|
# Lascia il valore VUOTO qui: cosi' la guardia ${POSTGRES_PASSWORD:?...} in
|
||||||
|
# docker-compose.yml fallisce in modo esplicito se dimentichi di valorizzarla
|
||||||
|
# nel tuo .env (un valore segnaposto come "change-me" soddisferebbe :? e farebbe
|
||||||
|
# partire il DB con una password nota).
|
||||||
|
# genera con: openssl rand -base64 32
|
||||||
|
POSTGRES_PASSWORD=
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
# Variabili d'ambiente con segreti (password DB, immagine, ecc.)
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
|
||||||
|
# Cartella IDE
|
||||||
|
.idea/
|
||||||
|
|
||||||
|
# Backup transitorio scritto da init-letsencrypt.sh durante il bootstrap ACME.
|
||||||
|
# Se lo script viene interrotto, il file resta sul disco e non va committato.
|
||||||
|
nginx/conf.d/*.bak
|
||||||
@@ -10,16 +10,16 @@ Questa configurazione fornisce un'infrastruttura completa per esporre un sito We
|
|||||||
```
|
```
|
||||||
.
|
.
|
||||||
├── docker-compose.yml
|
├── docker-compose.yml
|
||||||
|
├── .env.example # Template delle variabili d'ambiente (copia in .env)
|
||||||
|
├── .gitignore
|
||||||
├── init-letsencrypt.sh
|
├── init-letsencrypt.sh
|
||||||
├── renew-certificates.sh
|
├── renew-certificates.sh
|
||||||
<<<<<<< HEAD
|
|
||||||
=======
|
|
||||||
├── certbot-entrypoint.sh
|
├── certbot-entrypoint.sh
|
||||||
>>>>>>> 6b95df5 (modifica al funzionamento del certbot)
|
|
||||||
├── nginx/
|
├── nginx/
|
||||||
│ ├── nginx.conf
|
│ ├── nginx.conf
|
||||||
│ └── conf.d/
|
│ └── conf.d/
|
||||||
│ └── app.conf
|
│ ├── app.conf
|
||||||
|
│ └── security-headers.inc # Header di sicurezza condivisi (vedi sotto)
|
||||||
└── README.md
|
└── README.md
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -34,14 +34,31 @@ Questa configurazione fornisce un'infrastruttura completa per esporre un sito We
|
|||||||
|
|
||||||
### 1. Configura la tua applicazione
|
### 1. Configura la tua applicazione
|
||||||
|
|
||||||
Nel `docker-compose.yml`, modifica la sezione `app`:
|
Lo stack definisce quattro servizi: `blog` (l'applicazione Java/JHipster),
|
||||||
|
`postgresql` (il database), `nginx` (reverse proxy) e `certbot` (emissione e
|
||||||
|
rinnovo dei certificati). L'applicazione è raggiungibile **solo** tramite nginx:
|
||||||
|
la porta `8080` non è pubblicata sull'host.
|
||||||
|
|
||||||
```yaml
|
L'immagine dell'applicazione e la password del database si configurano tramite
|
||||||
app:
|
variabili d'ambiente. Copia `.env.example` in `.env` e valorizzalo:
|
||||||
image: your-java-app:latest # <-- Sostituisci con la tua immagine
|
|
||||||
# ... altre configurazioni
|
```bash
|
||||||
|
cp .env.example .env
|
||||||
```
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# .env (NON committare: contiene segreti)
|
||||||
|
# Usa un tag versionato o un digest, mai :latest, per deploy riproducibili
|
||||||
|
BLOG_IMAGE=registry.example.com/tuo-utente/blog:1.0.0
|
||||||
|
POSTGRES_PASSWORD=una-password-robusta
|
||||||
|
```
|
||||||
|
|
||||||
|
Il servizio `blog` nel `docker-compose.yml` usa `image: ${BLOG_IMAGE}` e passa a
|
||||||
|
Spring le credenziali del datasource (`SPRING_DATASOURCE_USERNAME=blog`,
|
||||||
|
`SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD}`). Il servizio `postgresql`
|
||||||
|
usa la stessa `POSTGRES_PASSWORD` e attende di essere `healthy` prima che `blog`
|
||||||
|
parta (`depends_on: condition: service_healthy`).
|
||||||
|
|
||||||
### 2. Prima configurazione dei certificati
|
### 2. Prima configurazione dei certificati
|
||||||
|
|
||||||
#### Opzione A: Script Automatico (Consigliato)
|
#### Opzione A: Script Automatico (Consigliato)
|
||||||
@@ -56,13 +73,56 @@ Usa lo script di inizializzazione:
|
|||||||
./init-letsencrypt.sh tuodominio.com tua-email@example.com 0
|
./init-letsencrypt.sh tuodominio.com tua-email@example.com 0
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> **Importante (staging → produzione)**: dopo il run di staging esiste già una
|
||||||
|
> lineage per il dominio, e `certbot certonly` (lanciato con `--non-interactive`)
|
||||||
|
> fallirebbe invece di sovrascriverla. Prima del run di produzione rimuovi la
|
||||||
|
> lineage di staging:
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> docker-compose run --rm certbot delete --cert-name tuodominio.com
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> In alternativa aggiungi `--force-renewal` alla chiamata `certonly`.
|
||||||
|
|
||||||
|
Lo script gestisce automaticamente il bootstrap: salva la configurazione HTTPS
|
||||||
|
committata, avvia nginx con una config temporanea solo-HTTP per il challenge ACME
|
||||||
|
e, una volta ottenuto il certificato, ripristina `app.conf` sostituendo il
|
||||||
|
placeholder `example.com` con il tuo dominio.
|
||||||
|
|
||||||
#### Opzione B: Manuale
|
#### Opzione B: Manuale
|
||||||
|
|
||||||
1. Modifica `nginx/conf.d/app.conf` sostituendo `example.com` con il tuo dominio
|
Su un host nuovo i certificati non esistono ancora, quindi nginx **non** può
|
||||||
|
caricare il blocco `server` HTTPS di `app.conf` (fallirebbe con "cannot load
|
||||||
|
certificate"). Serve quindi un bootstrap in due fasi.
|
||||||
|
|
||||||
2. Avvia solo nginx:
|
1. Salva la configurazione HTTPS e crea una config temporanea solo-HTTP per il
|
||||||
|
challenge ACME:
|
||||||
```bash
|
```bash
|
||||||
docker-compose up -d nginx
|
cp nginx/conf.d/app.conf nginx/conf.d/app.conf.bak
|
||||||
|
cat > nginx/conf.d/app.conf <<'EOF'
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name tuodominio.com www.tuodominio.com;
|
||||||
|
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
location / {
|
||||||
|
return 200 'Let\'s Encrypt initialization in progress...';
|
||||||
|
add_header Content-Type text/plain;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Avvia nginx senza dipendenze (solo per la fase ACME):
|
||||||
|
```bash
|
||||||
|
# --no-deps evita di avviare anche blog/postgresql: nginx ora dipende da blog
|
||||||
|
# (che attende postgresql healthy) e senza .env valorizzato fallirebbe. Per il
|
||||||
|
# challenge ACME la config temporanea non ha proxy_pass, quindi basta nginx.
|
||||||
|
docker-compose up -d --no-deps nginx
|
||||||
```
|
```
|
||||||
|
|
||||||
3. Richiedi il certificato:
|
3. Richiedi il certificato:
|
||||||
@@ -77,8 +137,16 @@ docker-compose run --rm certbot certonly \
|
|||||||
-d www.tuodominio.com
|
-d www.tuodominio.com
|
||||||
```
|
```
|
||||||
|
|
||||||
4. Ricarica nginx:
|
4. Ripristina la configurazione HTTPS, sostituisci il placeholder, avvia l'intero
|
||||||
|
stack (così `blog` è risolvibile dal proxy), **valida** e ricarica nginx:
|
||||||
```bash
|
```bash
|
||||||
|
mv nginx/conf.d/app.conf.bak nginx/conf.d/app.conf
|
||||||
|
sed -i "s/example.com/tuodominio.com/g" nginx/conf.d/app.conf
|
||||||
|
# Avvia blog + postgresql prima del reload: altrimenti il proxy_pass verso "blog"
|
||||||
|
# non sarebbe risolvibile.
|
||||||
|
docker-compose up -d
|
||||||
|
# nginx -s reload esce 0 anche con config invalida: valida prima con nginx -t.
|
||||||
|
docker-compose exec nginx nginx -t
|
||||||
docker-compose exec nginx nginx -s reload
|
docker-compose exec nginx nginx -s reload
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -98,6 +166,24 @@ Questo permette di:
|
|||||||
- Avere il servizio sempre attivo per il rinnovo automatico con `docker-compose up -d`
|
- Avere il servizio sempre attivo per il rinnovo automatico con `docker-compose up -d`
|
||||||
- Eseguire comandi manuali con `docker-compose run --rm certbot <comando>`
|
- Eseguire comandi manuali con `docker-compose run --rm certbot <comando>`
|
||||||
|
|
||||||
|
> **Reload di nginx dopo il rinnovo**: nginx legge i certificati in memoria una
|
||||||
|
> sola volta (all'avvio o a un reload) e non si accorge da solo dei file
|
||||||
|
> rinnovati sul volume. Per questo il servizio `nginx` nel `docker-compose.yml`
|
||||||
|
> esegue un reload periodico (ogni 6 ore):
|
||||||
|
>
|
||||||
|
> ```yaml
|
||||||
|
> command: sh -c "while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g 'daemon off;'"
|
||||||
|
> ```
|
||||||
|
>
|
||||||
|
> Senza questo meccanismo il sito servirebbe un certificato scaduto ~90 giorni
|
||||||
|
> dopo la prima emissione, anche se certbot lo ha rinnovato correttamente.
|
||||||
|
> Verifica le date del certificato servito con:
|
||||||
|
>
|
||||||
|
> ```bash
|
||||||
|
> docker-compose exec nginx openssl x509 \
|
||||||
|
> -in /etc/letsencrypt/live/tuodominio.com/fullchain.pem -noout -dates
|
||||||
|
> ```
|
||||||
|
|
||||||
Let's Encrypt invia email di promemoria a 20, 10 e 1 giorno dalla scadenza.
|
Let's Encrypt invia email di promemoria a 20, 10 e 1 giorno dalla scadenza.
|
||||||
|
|
||||||
### Verifica Manuale del Rinnovo
|
### Verifica Manuale del Rinnovo
|
||||||
@@ -119,7 +205,10 @@ docker-compose run --rm certbot renew --force-renewal
|
|||||||
docker-compose logs -f nginx
|
docker-compose logs -f nginx
|
||||||
|
|
||||||
# Log applicazione
|
# Log applicazione
|
||||||
docker-compose logs -f app
|
docker-compose logs -f blog
|
||||||
|
|
||||||
|
# Log database PostgreSQL
|
||||||
|
docker-compose logs -f postgresql
|
||||||
|
|
||||||
# Log certbot
|
# Log certbot
|
||||||
docker-compose logs certbot
|
docker-compose logs certbot
|
||||||
@@ -148,20 +237,37 @@ docker-compose run --rm certbot certificates
|
|||||||
|
|
||||||
### Headers di Sicurezza
|
### Headers di Sicurezza
|
||||||
|
|
||||||
La configurazione include:
|
Gli header sono centralizzati nello snippet `nginx/conf.d/security-headers.inc`,
|
||||||
- HSTS (HTTP Strict Transport Security)
|
incluso nel server block (ed ereditato dalle location). nginx si limita agli
|
||||||
- X-Frame-Options
|
header che l'applicazione non può impostare correttamente o che non entrano in
|
||||||
- X-Content-Type-Options
|
conflitto con quelli emessi da JHipster:
|
||||||
- X-XSS-Protection
|
- HSTS (HTTP Strict Transport Security) — `max-age=31536000` **senza**
|
||||||
- OCSP Stapling
|
`includeSubDomains`/`preload` (flag difficili da revocare: aggiungili solo dopo
|
||||||
|
aver verificato che tutti i sottodomini siano HTTPS-only ed esserti iscritto a
|
||||||
|
hstspreload.org)
|
||||||
|
- X-Content-Type-Options `nosniff`
|
||||||
|
- X-XSS-Protection impostato a `0` (l'auditor legacy è deprecato)
|
||||||
|
|
||||||
|
> Nota: `Content-Security-Policy`, `X-Frame-Options`, `Referrer-Policy` e
|
||||||
|
> `Permissions-Policy` **non** sono impostati qui: li emette già JHipster
|
||||||
|
> (`SecurityConfiguration`). Poiché in nginx `add_header` non sostituisce gli
|
||||||
|
> header dell'upstream, duplicarli manderebbe al browser header conflittuali
|
||||||
|
> (es. due CSP, di cui vale l'intersezione più restrittiva). Se vuoi che sia
|
||||||
|
> nginx a governarli, usa `proxy_hide_header` nelle location e verifica in
|
||||||
|
> staging che il bundle dell'app non si rompa.
|
||||||
|
|
||||||
|
> Nota: l'OCSP Stapling è stato rimosso perché Let's Encrypt non include più
|
||||||
|
> l'URL del responder OCSP nei certificati e ha dismesso il servizio.
|
||||||
|
|
||||||
### WebSocket Support
|
### WebSocket Support
|
||||||
|
|
||||||
Il proxy è già configurato per supportare WebSocket. Se la tua applicazione non li usa, puoi rimuovere:
|
Il proxy è già configurato per supportare WebSocket tramite la map
|
||||||
|
`$connection_upgrade` definita in `nginx.conf` (invia `Connection: upgrade` solo
|
||||||
|
quando il client lo richiede). Se la tua applicazione non li usa, puoi rimuovere:
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection "upgrade";
|
proxy_set_header Connection $connection_upgrade;
|
||||||
```
|
```
|
||||||
|
|
||||||
### Timeout e Buffer
|
### Timeout e Buffer
|
||||||
@@ -180,44 +286,67 @@ Se usi JHipster, considera:
|
|||||||
|
|
||||||
### 1. Variabili d'Ambiente
|
### 1. Variabili d'Ambiente
|
||||||
|
|
||||||
|
Il servizio `blog` è già configurato per JHipster in profilo `prod`:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
app:
|
blog:
|
||||||
environment:
|
environment:
|
||||||
- SPRING_PROFILES_ACTIVE=prod
|
- SPRING_PROFILES_ACTIVE=prod
|
||||||
- JHIPSTER_SECURITY_AUTHENTICATION_JWT_BASE64_SECRET=your-secret
|
- SPRING_DATASOURCE_URL=jdbc:postgresql://postgresql:5432/blog
|
||||||
- SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/yourdb
|
- SPRING_DATASOURCE_USERNAME=blog
|
||||||
|
- SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Eventuali segreti aggiuntivi (es. `JHIPSTER_SECURITY_AUTHENTICATION_JWT_BASE64_SECRET`)
|
||||||
|
vanno passati tramite variabili d'ambiente da `.env`, mai committati nel repository.
|
||||||
|
|
||||||
|
> Nota: il profilo `api-docs` (Swagger UI e `/v3/api-docs`) **non** è attivo in
|
||||||
|
> produzione, perché nginx proxya tutto `/` e renderebbe pubbliche quelle pagine.
|
||||||
|
> Attivalo solo in ambienti non esposti.
|
||||||
|
|
||||||
### 2. Database PostgreSQL
|
### 2. Database PostgreSQL
|
||||||
|
|
||||||
Aggiungi al `docker-compose.yml`:
|
Il database è già incluso nello stack come servizio `postgresql`
|
||||||
|
(`postgres:17.11`, volume `postgresql-data`). La password **non** è hardcoded:
|
||||||
|
viene letta da `POSTGRES_PASSWORD` nel file `.env` e condivisa con il servizio `blog`.
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
services:
|
postgresql:
|
||||||
db:
|
image: postgres:17.11
|
||||||
image: postgres:15-alpine
|
|
||||||
environment:
|
environment:
|
||||||
- POSTGRES_USER=yourapp
|
- POSTGRES_USER=blog
|
||||||
- POSTGRES_PASSWORD=yourpassword
|
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
|
||||||
- POSTGRES_DB=yourdb
|
|
||||||
volumes:
|
volumes:
|
||||||
- postgres-data:/var/lib/postgresql/data
|
- postgresql-data:/var/lib/postgresql/data/
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
|
|
||||||
volumes:
|
|
||||||
postgres-data:
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
La porta `5432` **non** è pubblicata sull'host: il database è raggiungibile solo
|
||||||
|
dai container sulla rete interna `app-network`.
|
||||||
|
|
||||||
### 3. Health Check Endpoint
|
### 3. Health Check Endpoint
|
||||||
|
|
||||||
JHipster espone `/management/health`:
|
Il servizio `blog` definisce un healthcheck sull'endpoint JHipster
|
||||||
|
`/management/health` (via `wget`, perché le immagini JRE slim non sempre includono
|
||||||
|
`curl`):
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:8080/management/health"]
|
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/management/health || exit 1"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 10s
|
||||||
|
retries: 5
|
||||||
|
start_period: 60s
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> Nota: Docker **non** riavvia un container solo perché il suo healthcheck è
|
||||||
|
> `unhealthy` — `restart: unless-stopped` agisce solo quando il processo
|
||||||
|
> principale termina. L'healthcheck serve per l'ordine di avvio
|
||||||
|
> (`depends_on: condition: service_healthy`) e per lo stato mostrato da
|
||||||
|
> `docker-compose ps`. Per il self-healing automatico aggiungi uno strumento
|
||||||
|
> come `willfarrell/autoheal`.
|
||||||
|
|
||||||
## Troubleshooting
|
## Troubleshooting
|
||||||
|
|
||||||
### Certificato Non Ottenuto
|
### Certificato Non Ottenuto
|
||||||
@@ -239,9 +368,11 @@ docker-compose logs nginx
|
|||||||
|
|
||||||
### Applicazione Non Raggiungibile
|
### Applicazione Non Raggiungibile
|
||||||
|
|
||||||
1. Verifica che l'app sia in esecuzione: `docker-compose ps`
|
1. Verifica che i servizi siano in esecuzione: `docker-compose ps`
|
||||||
2. Controlla i log dell'app: `docker-compose logs app`
|
2. Controlla i log dell'app: `docker-compose logs blog`
|
||||||
3. Verifica la connettività: `docker-compose exec nginx curl http://app:8080`
|
3. Verifica la connettività: `docker-compose exec nginx curl http://blog:8080`
|
||||||
|
4. Verifica lo stato di PostgreSQL: `docker-compose ps postgresql` e
|
||||||
|
`docker-compose exec postgresql pg_isready -U blog`
|
||||||
|
|
||||||
### Rate Limit Let's Encrypt
|
### Rate Limit Let's Encrypt
|
||||||
|
|
||||||
@@ -277,7 +408,7 @@ docker-compose up -d
|
|||||||
docker-compose run --rm certbot certificates
|
docker-compose run --rm certbot certificates
|
||||||
|
|
||||||
# Verifica SSL del sito
|
# Verifica SSL del sito
|
||||||
curl -vI https://www.elenabaracchini.it 2>&1 | grep -A 10 "SSL certificate"
|
curl -vI https://www.tuodominio.com 2>&1 | grep -A 10 "SSL certificate"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Log Rotation
|
### Log Rotation
|
||||||
|
|||||||
+63
-17
@@ -1,32 +1,76 @@
|
|||||||
version: '3.8'
|
|
||||||
|
|
||||||
services:
|
services:
|
||||||
# Java Web Application
|
blog:
|
||||||
app:
|
# Immagine versionata/digest tramite variabile d'ambiente (vedi .env).
|
||||||
image: your-java-app:latest
|
# Evita :latest in produzione per avere deploy riproducibili.
|
||||||
container_name: java-app
|
image: "${BLOG_IMAGE:?BLOG_IMAGE non impostata: copia .env.example in .env}"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
environment:
|
environment:
|
||||||
|
- _JAVA_OPTIONS=-Xmx512m -Xms256m
|
||||||
- SPRING_PROFILES_ACTIVE=prod
|
- SPRING_PROFILES_ACTIVE=prod
|
||||||
- SERVER_PORT=8080
|
- MANAGEMENT_PROMETHEUS_METRICS_EXPORT_ENABLED=true
|
||||||
|
- SPRING_DATASOURCE_URL=jdbc:postgresql://postgresql:5432/blog
|
||||||
|
- SPRING_DATASOURCE_USERNAME=blog
|
||||||
|
- SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD non impostata, vedi .env.example}
|
||||||
|
- SPRING_LIQUIBASE_URL=jdbc:postgresql://postgresql:5432/blog
|
||||||
|
# Non esporre la porta 8080 sull'host: l'app deve essere raggiungibile
|
||||||
|
# solo tramite nginx (TLS/HSTS/header di sicurezza).
|
||||||
|
# Per debug locale, decommenta e usa il binding su loopback:
|
||||||
# ports:
|
# ports:
|
||||||
# - "8080:8080" # Non esporre direttamente, usa nginx
|
# - 127.0.0.1:8080:8080
|
||||||
volumes:
|
depends_on:
|
||||||
- app-data:/app/data
|
postgresql:
|
||||||
|
condition: service_healthy
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "curl", "-f", "http://localhost:8080/actuator/health"]
|
# JHipster espone l'endpoint /management/health. Usiamo wget perché le
|
||||||
|
# immagini JRE slim non sempre includono curl. L'healthcheck serve per
|
||||||
|
# l'ordine di avvio e per lo stato in "docker-compose ps": Docker NON
|
||||||
|
# riavvia un container perché "unhealthy" (restart agisce solo all'uscita
|
||||||
|
# del processo); per il self-healing usa uno strumento come willfarrell/autoheal.
|
||||||
|
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/management/health || exit 1"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
timeout: 10s
|
timeout: 10s
|
||||||
retries: 3
|
retries: 5
|
||||||
start_period: 40s
|
start_period: 60s
|
||||||
|
|
||||||
|
postgresql:
|
||||||
|
image: postgres:17.11
|
||||||
|
restart: unless-stopped
|
||||||
|
volumes:
|
||||||
|
- postgresql-data:/var/lib/postgresql/data/
|
||||||
|
networks:
|
||||||
|
- app-network
|
||||||
|
environment:
|
||||||
|
- POSTGRES_USER=blog
|
||||||
|
# Nome del database esplicito: senza questa riga l'immagine usa POSTGRES_USER
|
||||||
|
# come default. Dichiararlo evita che, cambiando l'utente in futuro, cambi
|
||||||
|
# anche il nome del DB rompendo silenziosamente l'URL JDBC del servizio blog.
|
||||||
|
- POSTGRES_DB=blog
|
||||||
|
# Password letta da .env (non committato). Niente auth "trust" in produzione.
|
||||||
|
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?POSTGRES_PASSWORD non impostata, vedi .env.example}
|
||||||
|
healthcheck:
|
||||||
|
# Forza il TCP (-h localhost) e nomina il database per non risultare
|
||||||
|
# "healthy" durante il bootstrap initdb, quando esiste solo il server temporaneo.
|
||||||
|
test: [ 'CMD-SHELL', 'pg_isready -h localhost -U $${POSTGRES_USER} -d $${POSTGRES_USER}' ]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 10
|
||||||
|
# PostgreSQL è raggiungibile solo tramite la rete interna app-network.
|
||||||
|
# Non pubblicare la porta 5432 sull'host in produzione.
|
||||||
|
|
||||||
# Nginx Reverse Proxy
|
# Nginx Reverse Proxy
|
||||||
nginx:
|
nginx:
|
||||||
image: nginx:alpine
|
# Versione pinnata per deploy riproducibili (http2 come direttiva, vedi app.conf).
|
||||||
|
# Branch stabile corrente: la 1.27 mainline e' stata superata ad aprile 2025 e
|
||||||
|
# non riceve piu' fix di sicurezza, quindi usiamo la stable 1.30.
|
||||||
|
image: nginx:1.30-alpine
|
||||||
container_name: nginx-proxy
|
container_name: nginx-proxy
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
# Ricarica periodica per far rileggere a nginx i certificati rinnovati da
|
||||||
|
# certbot: nginx tiene i certificati in memoria e senza un reload servirebbe
|
||||||
|
# un certificato scaduto ~90 giorni dopo la prima emissione.
|
||||||
|
command: sh -c "while :; do sleep 6h & wait $${!}; nginx -s reload; done & nginx -g 'daemon off;'"
|
||||||
ports:
|
ports:
|
||||||
- "80:80"
|
- "80:80"
|
||||||
- "443:443"
|
- "443:443"
|
||||||
@@ -39,7 +83,7 @@ services:
|
|||||||
networks:
|
networks:
|
||||||
- app-network
|
- app-network
|
||||||
depends_on:
|
depends_on:
|
||||||
- app
|
- blog
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "nginx", "-t"]
|
test: ["CMD", "nginx", "-t"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
@@ -48,7 +92,9 @@ services:
|
|||||||
|
|
||||||
# Certbot per Let's Encrypt - Auto Renewal
|
# Certbot per Let's Encrypt - Auto Renewal
|
||||||
certbot:
|
certbot:
|
||||||
image: certbot/certbot:latest
|
# Pin a una versione precisa (coerente con la policy "no :latest in produzione"):
|
||||||
|
# una release certbot con breaking change romperebbe silenziosamente l'auto-renewal.
|
||||||
|
image: certbot/certbot:v5.4.0
|
||||||
container_name: certbot
|
container_name: certbot
|
||||||
volumes:
|
volumes:
|
||||||
- certbot-webroot:/var/www/certbot:rw
|
- certbot-webroot:/var/www/certbot:rw
|
||||||
@@ -65,7 +111,7 @@ networks:
|
|||||||
driver: bridge
|
driver: bridge
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
app-data:
|
postgresql-data:
|
||||||
certbot-webroot:
|
certbot-webroot:
|
||||||
certbot-certs:
|
certbot-certs:
|
||||||
certbot-lib:
|
certbot-lib:
|
||||||
|
|||||||
+70
-18
@@ -20,7 +20,30 @@ echo "### Inizializzazione certificati Let's Encrypt per $DOMAIN"
|
|||||||
# Crea directory temporanea per configurazione nginx
|
# Crea directory temporanea per configurazione nginx
|
||||||
mkdir -p ./nginx/conf.d
|
mkdir -p ./nginx/conf.d
|
||||||
|
|
||||||
# Crea configurazione nginx temporanea (solo HTTP)
|
# Salva la configurazione HTTPS committata: va ripristinata dopo l'emissione.
|
||||||
|
# Su un host nuovo i certificati non esistono ancora, quindi nginx non può
|
||||||
|
# caricare il blocco server HTTPS; usiamo prima una config solo-HTTP.
|
||||||
|
#
|
||||||
|
# Guardia: se un run precedente è stato ucciso (SIGKILL/reboot) prima del
|
||||||
|
# ripristino, su disco app.conf è la config temporanea solo-HTTP mentre
|
||||||
|
# app.conf.bak contiene la vera config HTTPS. Un semplice cp sovrascriverebbe
|
||||||
|
# il backup buono con quello temporaneo, perdendo la config HTTPS. Quindi, se il
|
||||||
|
# backup esiste già, lo ripristiniamo prima di ricominciare.
|
||||||
|
if [ -f ./nginx/conf.d/app.conf.bak ]; then
|
||||||
|
echo "### Trovato app.conf.bak di un run precedente: ripristino prima di procedere"
|
||||||
|
mv ./nginx/conf.d/app.conf.bak ./nginx/conf.d/app.conf
|
||||||
|
fi
|
||||||
|
cp ./nginx/conf.d/app.conf ./nginx/conf.d/app.conf.bak
|
||||||
|
|
||||||
|
# Ripristina sempre la configurazione committata all'uscita dello script
|
||||||
|
restore_conf() {
|
||||||
|
if [ -f ./nginx/conf.d/app.conf.bak ]; then
|
||||||
|
mv ./nginx/conf.d/app.conf.bak ./nginx/conf.d/app.conf
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
trap restore_conf EXIT
|
||||||
|
|
||||||
|
# Crea configurazione nginx temporanea (solo HTTP) per il challenge ACME
|
||||||
cat >./nginx/conf.d/app.conf <<EOF
|
cat >./nginx/conf.d/app.conf <<EOF
|
||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
@@ -38,11 +61,24 @@ server {
|
|||||||
}
|
}
|
||||||
EOF
|
EOF
|
||||||
|
|
||||||
echo "### Avvio nginx e certbot..."
|
echo "### Avvio nginx (solo HTTP, senza dipendenze) per il challenge ACME..."
|
||||||
docker-compose up -d nginx
|
# --no-deps: nginx ora dipende da blog (che attende postgresql healthy); per la
|
||||||
|
# fase ACME la config temporanea non ha proxy_pass, quindi serve solo nginx.
|
||||||
|
docker-compose up -d --no-deps nginx
|
||||||
|
|
||||||
echo "### Attendo che nginx sia pronto..."
|
echo "### Attendo che nginx sia pronto..."
|
||||||
sleep 5
|
# Invece di uno sleep fisso, aspettiamo che nginx risponda davvero.
|
||||||
|
for i in $(seq 1 30); do
|
||||||
|
if curl -sf http://localhost/ >/dev/null 2>&1; then
|
||||||
|
echo "### nginx è pronto"
|
||||||
|
break
|
||||||
|
fi
|
||||||
|
if [ "$i" -eq 30 ]; then
|
||||||
|
echo "### nginx non risponde dopo l'attesa, interrompo" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
sleep 1
|
||||||
|
done
|
||||||
|
|
||||||
echo "### Richiesta certificato per $DOMAIN..."
|
echo "### Richiesta certificato per $DOMAIN..."
|
||||||
|
|
||||||
@@ -55,30 +91,46 @@ else
|
|||||||
echo "### Modalità PRODUCTION"
|
echo "### Modalità PRODUCTION"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Richiedi il certificato
|
# Richiedi il certificato.
|
||||||
|
# --non-interactive: se esiste già una lineage per il dominio (es. flusso
|
||||||
|
# staging->produzione o un semplice re-run), certbot si fermerebbe su un prompt
|
||||||
|
# interattivo "Keep/Renew"; cosi' invece fallisce in modo esplicito.
|
||||||
|
# Per passare da staging a produzione usa --force-renewal (o prima
|
||||||
|
# "docker-compose run --rm certbot delete --cert-name $DOMAIN").
|
||||||
docker-compose run --rm certbot certonly \
|
docker-compose run --rm certbot certonly \
|
||||||
--webroot \
|
--webroot \
|
||||||
--webroot-path=/var/www/certbot \
|
--webroot-path=/var/www/certbot \
|
||||||
--email $EMAIL \
|
--email "$EMAIL" \
|
||||||
--agree-tos \
|
--agree-tos \
|
||||||
--no-eff-email \
|
--no-eff-email \
|
||||||
|
--non-interactive \
|
||||||
$STAGING_ARG \
|
$STAGING_ARG \
|
||||||
-d $DOMAIN \
|
-d "$DOMAIN" \
|
||||||
-d www.$DOMAIN
|
-d "www.$DOMAIN"
|
||||||
|
|
||||||
if [ $? -eq 0 ]; then
|
|
||||||
echo "### Certificato ottenuto con successo!"
|
echo "### Certificato ottenuto con successo!"
|
||||||
echo "### Aggiornamento configurazione nginx con HTTPS..."
|
echo "### Ripristino configurazione nginx HTTPS..."
|
||||||
|
|
||||||
# Sostituisci example.com con il dominio reale nella configurazione
|
# Ripristina la configurazione HTTPS committata (rimuove il backup) e sostituisci
|
||||||
sed -i "s/elenabaracchini\.it/$DOMAIN/g" ./nginx/conf.d/app.conf
|
# il placeholder example.com con il dominio reale.
|
||||||
|
restore_conf
|
||||||
|
sed -i "s/example\.com/$DOMAIN/g" ./nginx/conf.d/app.conf
|
||||||
|
|
||||||
# Ricarica nginx
|
# Avvia l'intero stack (blog + postgresql) cosi' che l'hostname "blog" sia
|
||||||
|
# risolvibile quando nginx carica il blocco HTTPS con il proxy_pass.
|
||||||
|
echo "### Avvio dell'intero stack..."
|
||||||
|
docker-compose up -d
|
||||||
|
|
||||||
|
# Valida la configurazione PRIMA di ricaricare: "nginx -s reload" esce 0 anche
|
||||||
|
# se la nuova config è invalida (cert mancante, upstream non risolvibile), e
|
||||||
|
# nginx continuerebbe a servire la vecchia config solo-HTTP in silenzio.
|
||||||
|
# "nginx -t" esce non-zero in caso di errore, quindi set -e interrompe qui.
|
||||||
|
echo "### Validazione della configurazione nginx..."
|
||||||
|
docker-compose exec nginx nginx -t
|
||||||
|
|
||||||
|
# Ricarica nginx con la configurazione HTTPS definitiva
|
||||||
docker-compose exec nginx nginx -s reload
|
docker-compose exec nginx nginx -s reload
|
||||||
|
|
||||||
echo "### Configurazione completata!"
|
echo "### Configurazione completata!"
|
||||||
echo "### Il rinnovo automatico è attivo (ogni 12 ore)"
|
echo "### Il rinnovo automatico è attivo: certbot rinnova ogni 12 ore e il"
|
||||||
else
|
echo "### servizio nginx ricarica i certificati periodicamente (ogni 6 ore)."
|
||||||
echo "### Errore nell'ottenimento del certificato"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
+104
-3
@@ -1,14 +1,115 @@
|
|||||||
|
# Redirect HTTP to HTTPS
|
||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
listen [::]:80;
|
listen [::]:80;
|
||||||
server_name elenabaracchini.it www.elenabaracchini.it;
|
server_name example.com www.example.com;
|
||||||
|
|
||||||
|
# Location per la validazione Let's Encrypt
|
||||||
location /.well-known/acme-challenge/ {
|
location /.well-known/acme-challenge/ {
|
||||||
root /var/www/certbot;
|
root /var/www/certbot;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Redirect tutto il resto a HTTPS
|
||||||
location / {
|
location / {
|
||||||
return 200 'Let\'s Encrypt initialization in progress...';
|
return 301 https://$host$request_uri;
|
||||||
add_header Content-Type text/plain;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# HTTPS Server
|
||||||
|
server {
|
||||||
|
listen 443 ssl;
|
||||||
|
listen [::]:443 ssl;
|
||||||
|
# Il parametro http2 su listen è deprecato dalla 1.25.1: usa la direttiva.
|
||||||
|
http2 on;
|
||||||
|
server_name example.com www.example.com;
|
||||||
|
|
||||||
|
# Certificati SSL
|
||||||
|
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
|
||||||
|
|
||||||
|
# Configurazione SSL sicura (profilo Mozilla intermediate)
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
# Rimossi i cipher DHE-RSA-*: senza un file ssl_dhparam (nginx >=1.11 non ha
|
||||||
|
# parametri DH incorporati) non verrebbero mai negoziati, quindi li togliamo
|
||||||
|
# per mantenere la lista onesta. Aggiungi ssl_dhparam (ffdhe2048) se li vuoi.
|
||||||
|
ssl_ciphers 'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305';
|
||||||
|
ssl_prefer_server_ciphers off;
|
||||||
|
|
||||||
|
# Session resumption: senza questi ogni nuova connessione fa un full handshake.
|
||||||
|
ssl_session_cache shared:SSL:10m;
|
||||||
|
ssl_session_timeout 1d;
|
||||||
|
ssl_session_tickets off;
|
||||||
|
|
||||||
|
# Header di sicurezza (HSTS, X-Frame-Options, CSP, ...)
|
||||||
|
include /etc/nginx/conf.d/security-headers.inc;
|
||||||
|
|
||||||
|
# OCSP Stapling rimosso: Let's Encrypt non include più l'URL del responder
|
||||||
|
# OCSP (dal 2025) e ha dismesso il servizio, quindi lo stapling non farebbe
|
||||||
|
# altro che generare un warning all'avvio.
|
||||||
|
|
||||||
|
# Nessun access_log/error_log per-vhost: nell'immagine ufficiale solo
|
||||||
|
# /var/log/nginx/access.log e error.log sono linkati a stdout/stderr, quindi
|
||||||
|
# file dedicati non comparirebbero in "docker-compose logs nginx", crescerebbero
|
||||||
|
# senza rotazione e andrebbero persi alla ricreazione del container. Si usa
|
||||||
|
# l'access_log a livello http (main) definito in nginx.conf.
|
||||||
|
|
||||||
|
# Location per la validazione Let's Encrypt
|
||||||
|
location /.well-known/acme-challenge/ {
|
||||||
|
root /var/www/certbot;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Blocca l'actuator/metrics JHipster dall'esterno (health, prometheus, info...).
|
||||||
|
# L'endpoint health serve solo all'healthcheck interno al container.
|
||||||
|
# ^~ : disabilita il match delle location regex per questo prefisso (altrimenti
|
||||||
|
# un URI /management/...qualcosa.js verrebbe gestito da una location regex).
|
||||||
|
# Senza slash finale copre sia "/management" (pagina di discovery dell'actuator)
|
||||||
|
# sia "/management/...".
|
||||||
|
location ^~ /management {
|
||||||
|
return 404;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Resolver Docker interno per risolvere l'hostname a ogni richiesta.
|
||||||
|
# Senza questo, proxy_pass con hostname letterale viene risolto una sola
|
||||||
|
# volta all'avvio: dopo un "docker-compose up -d" il container blog puo'
|
||||||
|
# ottenere un nuovo IP e nginx continuerebbe a puntare a quello vecchio
|
||||||
|
# (errori 502) finche' non viene riavviato.
|
||||||
|
resolver 127.0.0.11 valid=30s ipv6=off;
|
||||||
|
|
||||||
|
# Proxy verso l'applicazione Java
|
||||||
|
location / {
|
||||||
|
# Usare una variabile forza nginx a risolvere l'upstream a runtime
|
||||||
|
# tramite il resolver sopra, invece che una sola volta all'avvio.
|
||||||
|
set $upstream_blog http://blog:8080;
|
||||||
|
proxy_pass $upstream_blog;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
|
||||||
|
# Headers per preservare informazioni client
|
||||||
|
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_set_header X-Forwarded-Host $host;
|
||||||
|
proxy_set_header X-Forwarded-Port $server_port;
|
||||||
|
|
||||||
|
# WebSocket support (se necessario): invia "upgrade" solo quando richiesto
|
||||||
|
# tramite la map $connection_upgrade definita in nginx.conf.
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $connection_upgrade;
|
||||||
|
|
||||||
|
# Timeout
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
proxy_send_timeout 60s;
|
||||||
|
proxy_read_timeout 60s;
|
||||||
|
|
||||||
|
# Buffer settings
|
||||||
|
proxy_buffering on;
|
||||||
|
proxy_buffer_size 4k;
|
||||||
|
proxy_buffers 8 4k;
|
||||||
|
proxy_busy_buffers_size 8k;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Le risorse statiche sono servite dallo stesso location / sopra: JHipster
|
||||||
|
# imposta gia' gli header di cache corretti (con max-age e hash nei nomi
|
||||||
|
# file dove appropriato), quindi non serve un location dedicato che
|
||||||
|
# duplicherebbe/entrebbe in conflitto con quegli header.
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
# Header di sicurezza, inclusi a livello di server block e quindi ereditati da
|
||||||
|
# tutte le location che non ridefiniscono i propri add_header.
|
||||||
|
# NB: in nginx un add_header dentro un location SOSTITUISCE tutti gli add_header
|
||||||
|
# ereditati dal server; se in futuro aggiungi una location con add_header propri,
|
||||||
|
# ri-includi questo snippet li' dentro.
|
||||||
|
# Il file ha estensione .inc per non essere caricato da "include conf.d/*.conf".
|
||||||
|
|
||||||
|
# Ownership degli header: JHipster (SecurityConfiguration) emette gia' la propria
|
||||||
|
# Content-Security-Policy, X-Frame-Options, Referrer-Policy e Permissions-Policy.
|
||||||
|
# In nginx add_header NON sostituisce gli header dell'upstream: il browser
|
||||||
|
# riceverebbe header duplicati/conflittuali (es. due CSP -> intersezione piu'
|
||||||
|
# restrittiva che puo' rompere il bundle Angular/React, due X-Frame-Options).
|
||||||
|
# Quindi quegli header li lasciamo all'applicazione; nginx si occupa solo di HSTS
|
||||||
|
# (che l'app non puo' impostare correttamente dietro la terminazione TLS) e di un
|
||||||
|
# paio di header non in conflitto.
|
||||||
|
|
||||||
|
# HSTS (HTTP Strict Transport Security).
|
||||||
|
# Partiamo con max-age di 1 anno SENZA includeSubDomains/preload: sono flag
|
||||||
|
# difficili da revocare (ogni sottodominio dovrebbe servire HTTPS valido) e
|
||||||
|
# "preload" andrebbe inviato solo dopo l'iscrizione su hstspreload.org.
|
||||||
|
# Aggiungi "includeSubDomains; preload" solo dopo aver verificato tutti i sottodomini.
|
||||||
|
add_header Strict-Transport-Security "max-age=31536000" always;
|
||||||
|
|
||||||
|
add_header X-Content-Type-Options "nosniff" always;
|
||||||
|
|
||||||
|
# X-XSS-Protection disabilitato: l'auditor legacy è deprecato (rischio XS-leak).
|
||||||
|
# Ci si affida alla Content-Security-Policy impostata dall'applicazione.
|
||||||
|
add_header X-XSS-Protection "0" always;
|
||||||
@@ -11,12 +11,23 @@ http {
|
|||||||
include /etc/nginx/mime.types;
|
include /etc/nginx/mime.types;
|
||||||
default_type application/octet-stream;
|
default_type application/octet-stream;
|
||||||
|
|
||||||
|
# Non esporre la versione esatta di nginx nell'header Server e nelle pagine
|
||||||
|
# di errore: rende meno banale il fingerprinting della versione.
|
||||||
|
server_tokens off;
|
||||||
|
|
||||||
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
|
||||||
'$status $body_bytes_sent "$http_referer" '
|
'$status $body_bytes_sent "$http_referer" '
|
||||||
'"$http_user_agent" "$http_x_forwarded_for"';
|
'"$http_user_agent" "$http_x_forwarded_for"';
|
||||||
|
|
||||||
access_log /var/log/nginx/access.log main;
|
access_log /var/log/nginx/access.log main;
|
||||||
|
|
||||||
|
# Supporto WebSocket: invia l'header Connection "upgrade" solo quando il
|
||||||
|
# client lo richiede, altrimenti "close" (mantiene il keep-alive upstream).
|
||||||
|
map $http_upgrade $connection_upgrade {
|
||||||
|
default upgrade;
|
||||||
|
'' close;
|
||||||
|
}
|
||||||
|
|
||||||
sendfile on;
|
sendfile on;
|
||||||
tcp_nopush on;
|
tcp_nopush on;
|
||||||
tcp_nodelay on;
|
tcp_nodelay on;
|
||||||
|
|||||||
Reference in new issue
Block a user