This commit is contained in:
255
docs/nginx-configuration.md
Normal file
255
docs/nginx-configuration.md
Normal file
@@ -0,0 +1,255 @@
|
|||||||
|
# Nginx Configuration для Dokku
|
||||||
|
|
||||||
|
## Обзор
|
||||||
|
|
||||||
|
Улучшенная конфигурация nginx для Dokku с поддержкой:
|
||||||
|
- Глобального gzip сжатия
|
||||||
|
- Продвинутых настроек прокси
|
||||||
|
- Безопасности и производительности
|
||||||
|
- Поддержки Dokku переменных
|
||||||
|
|
||||||
|
## Основные улучшения
|
||||||
|
|
||||||
|
### 1. Gzip сжатие
|
||||||
|
```nginx
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_proxied any;
|
||||||
|
gzip_comp_level 6;
|
||||||
|
gzip_types
|
||||||
|
text/plain
|
||||||
|
text/css
|
||||||
|
text/xml
|
||||||
|
text/javascript
|
||||||
|
application/javascript
|
||||||
|
application/xml+rss
|
||||||
|
application/json
|
||||||
|
application/xml
|
||||||
|
image/svg+xml
|
||||||
|
font/ttf
|
||||||
|
font/otf
|
||||||
|
font/woff
|
||||||
|
font/woff2;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Продвинутые настройки прокси
|
||||||
|
- **Proxy buffering**: Оптимизированные буферы для производительности
|
||||||
|
- **X-Forwarded headers**: Правильная передача заголовков прокси
|
||||||
|
- **Keepalive connections**: Поддержка постоянных соединений
|
||||||
|
- **Rate limiting**: Ограничение запросов для защиты от DDoS
|
||||||
|
|
||||||
|
### 3. Безопасность
|
||||||
|
- **Security headers**: HSTS, CSP, X-Frame-Options и др.
|
||||||
|
- **SSL/TLS**: Современные протоколы и шифры
|
||||||
|
- **Rate limiting**: Защита от атак
|
||||||
|
- **Content Security Policy**: Защита от XSS
|
||||||
|
|
||||||
|
### 4. Кэширование
|
||||||
|
- **Static assets**: Агрессивное кэширование (1 год)
|
||||||
|
- **Dynamic content**: Умеренное кэширование (10 минут)
|
||||||
|
- **GraphQL**: Отключение кэширования
|
||||||
|
- **API endpoints**: Умеренное кэширование (5 минут)
|
||||||
|
|
||||||
|
## Использование Dokku переменных
|
||||||
|
|
||||||
|
### Доступные переменные
|
||||||
|
- `{{ $.APP }}` - имя приложения
|
||||||
|
- `{{ $.SSL_SERVER_NAME }}` - домен для SSL
|
||||||
|
- `{{ $.NOSSL_SERVER_NAME }}` - домен для HTTP
|
||||||
|
- `{{ $.APP_SSL_PATH }}` - путь к SSL сертификатам
|
||||||
|
- `{{ $.DOKKU_ROOT }}` - корневая директория Dokku
|
||||||
|
|
||||||
|
### Настройка через nginx:set
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Установка формата логов
|
||||||
|
dokku nginx:set core access-log-format detailed
|
||||||
|
|
||||||
|
# Установка размера тела запроса
|
||||||
|
dokku nginx:set core client-max-body-size 100M
|
||||||
|
|
||||||
|
# Установка таймаутов
|
||||||
|
dokku nginx:set core proxy-read-timeout 60s
|
||||||
|
dokku nginx:set core proxy-connect-timeout 60s
|
||||||
|
|
||||||
|
# Отключение логов
|
||||||
|
dokku nginx:set core access-log-path off
|
||||||
|
dokku nginx:set core error-log-path off
|
||||||
|
```
|
||||||
|
|
||||||
|
### Поддерживаемые свойства
|
||||||
|
- `access-log-format` - формат access логов
|
||||||
|
- `access-log-path` - путь к access логам
|
||||||
|
- `client-max-body-size` - максимальный размер тела запроса
|
||||||
|
- `proxy-read-timeout` - таймаут чтения от прокси
|
||||||
|
- `proxy-connect-timeout` - таймаут подключения к прокси
|
||||||
|
- `proxy-send-timeout` - таймаут отправки к прокси
|
||||||
|
- `bind-address-ipv4` - привязка к IPv4 адресу
|
||||||
|
- `bind-address-ipv6` - привязка к IPv6 адресу
|
||||||
|
|
||||||
|
## Локации (Locations)
|
||||||
|
|
||||||
|
### 1. Основное приложение (`/`)
|
||||||
|
- Проксирование всех запросов
|
||||||
|
- Кэширование динамического контента
|
||||||
|
- Поддержка WebSocket
|
||||||
|
- Rate limiting
|
||||||
|
|
||||||
|
### 2. GraphQL (`/graphql`)
|
||||||
|
- Отключение кэширования
|
||||||
|
- Увеличенные таймауты (300s)
|
||||||
|
- Специальные заголовки кэширования
|
||||||
|
|
||||||
|
### 3. Статические файлы
|
||||||
|
- Агрессивное кэширование (1 год)
|
||||||
|
- Gzip сжатие
|
||||||
|
- Заголовки `immutable`
|
||||||
|
|
||||||
|
### 4. API endpoints (`/api/`)
|
||||||
|
- Умеренное кэширование (5 минут)
|
||||||
|
- Rate limiting
|
||||||
|
- Заголовки статуса кэша
|
||||||
|
|
||||||
|
### 5. Health check (`/health`)
|
||||||
|
- Отключение логов
|
||||||
|
- Отключение кэширования
|
||||||
|
- Быстрые ответы
|
||||||
|
|
||||||
|
## Мониторинг и логирование
|
||||||
|
|
||||||
|
### Логи
|
||||||
|
- **Access logs**: `/var/log/nginx/core-access.log`
|
||||||
|
- **Error logs**: `/var/log/nginx/core-error.log`
|
||||||
|
- **Custom formats**: JSON и detailed
|
||||||
|
|
||||||
|
### Команды для просмотра логов
|
||||||
|
```bash
|
||||||
|
# Access логи
|
||||||
|
dokku nginx:access-logs core
|
||||||
|
|
||||||
|
# Error логи
|
||||||
|
dokku nginx:error-logs core
|
||||||
|
|
||||||
|
# Следование за логами
|
||||||
|
dokku nginx:access-logs core -t
|
||||||
|
dokku nginx:error-logs core -t
|
||||||
|
```
|
||||||
|
|
||||||
|
### Дополнительные конфигурации
|
||||||
|
|
||||||
|
Для добавления custom log formats и других настроек, создайте файл на сервере Dokku:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Подключитесь к серверу Dokku
|
||||||
|
ssh dokku@your-server
|
||||||
|
|
||||||
|
# Создайте файл с log formats
|
||||||
|
sudo mkdir -p /etc/nginx/conf.d
|
||||||
|
sudo nano /etc/nginx/conf.d/00-log-formats.conf
|
||||||
|
```
|
||||||
|
|
||||||
|
Содержимое файла `/etc/nginx/conf.d/00-log-formats.conf`:
|
||||||
|
```nginx
|
||||||
|
# Custom log format for JSON logging (as per Dokku docs)
|
||||||
|
log_format json_combined escape=json
|
||||||
|
'{'
|
||||||
|
'"time_local":"$time_local",'
|
||||||
|
'"remote_addr":"$remote_addr",'
|
||||||
|
'"remote_user":"$remote_user",'
|
||||||
|
'"request":"$request",'
|
||||||
|
'"status":"$status",'
|
||||||
|
'"body_bytes_sent":"$body_bytes_sent",'
|
||||||
|
'"request_time":"$request_time",'
|
||||||
|
'"http_referrer":"$http_referer",'
|
||||||
|
'"http_user_agent":"$http_user_agent",'
|
||||||
|
'"http_x_forwarded_for":"$http_x_forwarded_for",'
|
||||||
|
'"http_x_forwarded_proto":"$http_x_forwarded_proto"'
|
||||||
|
'}';
|
||||||
|
|
||||||
|
# Custom log format for detailed access logs
|
||||||
|
log_format detailed
|
||||||
|
'$remote_addr - $remote_user [$time_local] '
|
||||||
|
'"$request" $status $body_bytes_sent '
|
||||||
|
'"$http_referer" "$http_user_agent" '
|
||||||
|
'rt=$request_time uct="$upstream_connect_time" '
|
||||||
|
'uht="$upstream_header_time" urt="$upstream_response_time"';
|
||||||
|
```
|
||||||
|
|
||||||
|
### Валидация конфигурации
|
||||||
|
```bash
|
||||||
|
# Проверка конфигурации
|
||||||
|
dokku nginx:validate-config core
|
||||||
|
|
||||||
|
# Пересборка конфигурации
|
||||||
|
dokku proxy:build-config core
|
||||||
|
```
|
||||||
|
|
||||||
|
## Производительность
|
||||||
|
|
||||||
|
### Оптимизации
|
||||||
|
1. **Gzip сжатие**: Уменьшение размера передаваемых данных
|
||||||
|
2. **Proxy buffering**: Оптимизация буферов
|
||||||
|
3. **Keepalive**: Переиспользование соединений
|
||||||
|
4. **Кэширование**: Уменьшение нагрузки на бэкенд
|
||||||
|
5. **Rate limiting**: Защита от перегрузки
|
||||||
|
|
||||||
|
### Мониторинг
|
||||||
|
- Заголовок `X-Cache-Status` для отслеживания кэша
|
||||||
|
- Детальные логи с временем ответа
|
||||||
|
- Метрики upstream соединений
|
||||||
|
|
||||||
|
## Безопасность
|
||||||
|
|
||||||
|
### Заголовки безопасности
|
||||||
|
- `Strict-Transport-Security`: Принудительный HTTPS
|
||||||
|
- `Content-Security-Policy`: Защита от XSS
|
||||||
|
- `X-Frame-Options`: Защита от clickjacking
|
||||||
|
- `X-Content-Type-Options`: Защита от MIME sniffing
|
||||||
|
- `Referrer-Policy`: Контроль referrer
|
||||||
|
|
||||||
|
### Rate Limiting
|
||||||
|
- Общие запросы: 20 r/s с burst 20
|
||||||
|
- API endpoints: 10 r/s
|
||||||
|
- GraphQL: 5 r/s
|
||||||
|
- Соединения: 100 одновременных
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### Частые проблемы
|
||||||
|
|
||||||
|
1. **SSL ошибки**
|
||||||
|
```bash
|
||||||
|
dokku certs:report core
|
||||||
|
dokku certs:add core <cert-file> <key-file>
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Проблемы с кэшем**
|
||||||
|
```bash
|
||||||
|
# Очистка кэша nginx
|
||||||
|
sudo rm -rf /var/cache/nginx/*
|
||||||
|
sudo systemctl reload nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Проблемы с логами**
|
||||||
|
```bash
|
||||||
|
# Проверка прав доступа
|
||||||
|
sudo chown -R nginx:nginx /var/log/nginx/
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Валидация конфигурации**
|
||||||
|
```bash
|
||||||
|
dokku nginx:validate-config core --clean
|
||||||
|
dokku proxy:build-config core
|
||||||
|
```
|
||||||
|
|
||||||
|
## Обновление конфигурации
|
||||||
|
|
||||||
|
После изменения `nginx.conf.sigil`:
|
||||||
|
```bash
|
||||||
|
git add nginx.conf.sigil
|
||||||
|
git commit -m "Update nginx configuration"
|
||||||
|
git push dokku dev:dev
|
||||||
|
```
|
||||||
|
|
||||||
|
Конфигурация автоматически пересоберется при деплое.
|
130
nginx.conf.sigil
130
nginx.conf.sigil
@@ -1,80 +1,152 @@
|
|||||||
|
# Global cache configuration
|
||||||
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=discoursio_cache:10m max_size=1g inactive=60m use_temp_path=off;
|
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=discoursio_cache:10m max_size=1g inactive=60m use_temp_path=off;
|
||||||
|
|
||||||
|
# Rate limiting zones
|
||||||
limit_conn_zone $binary_remote_addr zone=addr:10m;
|
limit_conn_zone $binary_remote_addr zone=addr:10m;
|
||||||
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=20r/s;
|
limit_req_zone $binary_remote_addr zone=req_zone:10m rate=20r/s;
|
||||||
|
|
||||||
|
# HTTP to HTTPS redirect
|
||||||
server {
|
server {
|
||||||
listen 80;
|
listen 80;
|
||||||
server_name {{ $.NOSSL_SERVER_NAME }};
|
server_name {{ $.NOSSL_SERVER_NAME }};
|
||||||
return 301 https://$host$request_uri;
|
return 301 https://$host$request_uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Main HTTPS server
|
||||||
server {
|
server {
|
||||||
listen 443 ssl http2;
|
listen 443 ssl http2;
|
||||||
server_name {{ $.NOSSL_SERVER_NAME }};
|
server_name {{ $.SSL_SERVER_NAME }};
|
||||||
|
|
||||||
|
# SSL configuration
|
||||||
ssl_certificate {{ $.APP_SSL_PATH }}/server.crt;
|
ssl_certificate {{ $.APP_SSL_PATH }}/server.crt;
|
||||||
ssl_certificate_key {{ $.APP_SSL_PATH }}/server.key;
|
ssl_certificate_key {{ $.APP_SSL_PATH }}/server.key;
|
||||||
|
|
||||||
# Secure SSL protocols and ciphers
|
|
||||||
ssl_protocols TLSv1.2 TLSv1.3;
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
ssl_prefer_server_ciphers on;
|
ssl_prefer_server_ciphers off;
|
||||||
ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
|
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
|
||||||
ssl_session_cache shared:SSL:10m;
|
ssl_session_cache shared:SSL:10m;
|
||||||
ssl_session_timeout 10m;
|
ssl_session_timeout 10m;
|
||||||
ssl_session_tickets off;
|
ssl_session_tickets off;
|
||||||
|
|
||||||
|
# Gzip configuration
|
||||||
|
gzip on;
|
||||||
|
gzip_vary on;
|
||||||
|
gzip_min_length 1024;
|
||||||
|
gzip_proxied any;
|
||||||
|
gzip_comp_level 6;
|
||||||
|
gzip_types
|
||||||
|
text/plain
|
||||||
|
text/css
|
||||||
|
text/xml
|
||||||
|
text/javascript
|
||||||
|
application/javascript
|
||||||
|
application/xml+rss
|
||||||
|
application/json
|
||||||
|
application/xml
|
||||||
|
image/svg+xml
|
||||||
|
font/ttf
|
||||||
|
font/otf
|
||||||
|
font/woff
|
||||||
|
font/woff2;
|
||||||
|
|
||||||
# Security headers
|
# Security headers
|
||||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
|
||||||
add_header X-Frame-Options SAMEORIGIN;
|
add_header X-Frame-Options SAMEORIGIN always;
|
||||||
add_header X-XSS-Protection "1; mode=block";
|
add_header X-Content-Type-Options nosniff always;
|
||||||
add_header X-Content-Type-Options nosniff;
|
add_header X-XSS-Protection "1; mode=block" always;
|
||||||
|
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||||
|
|
||||||
# Logging
|
# Logging
|
||||||
access_log /var/log/nginx/{{ $.APP }}-access.log;
|
access_log /var/log/nginx/{{ $.APP }}-access.log;
|
||||||
error_log /var/log/nginx/{{ $.APP }}-error.log;
|
error_log /var/log/nginx/{{ $.APP }}-error.log;
|
||||||
|
|
||||||
# Performance and security settings
|
# Performance settings
|
||||||
client_max_body_size 100M;
|
client_max_body_size 100M;
|
||||||
client_header_timeout 10s;
|
client_header_timeout 60s;
|
||||||
client_body_timeout 10s;
|
client_body_timeout 60s;
|
||||||
send_timeout 10s;
|
send_timeout 60s;
|
||||||
keepalive_timeout 70;
|
keepalive_timeout 65s;
|
||||||
keepalive_requests 500;
|
keepalive_requests 1000;
|
||||||
proxy_read_timeout 3600;
|
|
||||||
|
|
||||||
location ~* ^/(?:graphql)?$ {
|
# Rate limiting
|
||||||
|
limit_conn addr 100;
|
||||||
|
limit_req zone=req_zone burst=20 nodelay;
|
||||||
|
|
||||||
|
# Main application proxy
|
||||||
|
location / {
|
||||||
proxy_pass http://{{ $.APP }}-8000;
|
proxy_pass http://{{ $.APP }}-8000;
|
||||||
proxy_http_version 1.1;
|
proxy_http_version 1.1;
|
||||||
proxy_set_header Upgrade $http_upgrade;
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
proxy_set_header Connection $http_connection;
|
proxy_set_header Connection $http_connection;
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_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-Port $server_port;
|
||||||
proxy_set_header X-Request-Start $msec;
|
proxy_set_header X-Request-Start $msec;
|
||||||
|
|
||||||
# Cache settings
|
# Proxy buffering
|
||||||
|
proxy_buffering on;
|
||||||
|
proxy_buffer_size 4k;
|
||||||
|
proxy_buffers 8 4k;
|
||||||
|
proxy_busy_buffers_size 8k;
|
||||||
|
|
||||||
|
# Cache settings for dynamic content
|
||||||
proxy_cache discoursio_cache;
|
proxy_cache discoursio_cache;
|
||||||
proxy_cache_revalidate on;
|
proxy_cache_revalidate on;
|
||||||
proxy_cache_min_uses 2;
|
proxy_cache_min_uses 1;
|
||||||
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
|
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
|
||||||
proxy_cache_background_update on;
|
proxy_cache_background_update on;
|
||||||
proxy_cache_lock on;
|
proxy_cache_lock on;
|
||||||
|
proxy_cache_valid 200 302 10m;
|
||||||
|
proxy_cache_valid 404 1m;
|
||||||
}
|
}
|
||||||
|
|
||||||
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|eot|svg)$ {
|
# GraphQL endpoint with specific settings
|
||||||
|
location /graphql {
|
||||||
|
proxy_pass http://{{ $.APP }}-8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection $http_connection;
|
||||||
|
proxy_set_header Host $http_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-Port $server_port;
|
||||||
|
proxy_set_header X-Request-Start $msec;
|
||||||
|
|
||||||
|
# Large buffering for GraphQL responses
|
||||||
|
proxy_buffering on;
|
||||||
|
proxy_buffer_size 8k;
|
||||||
|
proxy_buffers 16 8k;
|
||||||
|
proxy_busy_buffers_size 16k;
|
||||||
|
|
||||||
|
# GraphQL specific timeouts
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
proxy_send_timeout 60s;
|
||||||
|
|
||||||
|
# Disable caching for GraphQL
|
||||||
|
proxy_cache off;
|
||||||
|
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||||
|
add_header Pragma "no-cache";
|
||||||
|
add_header Expires "0";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Static assets with aggressive caching
|
||||||
|
location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|otf)$ {
|
||||||
proxy_pass http://{{ $.APP }}-8000;
|
proxy_pass http://{{ $.APP }}-8000;
|
||||||
proxy_set_header Host $http_host;
|
proxy_set_header Host $http_host;
|
||||||
expires 30d;
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
add_header Cache-Control "public, no-transform";
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
|
||||||
# Gzip settings for static files
|
# Aggressive caching for static assets
|
||||||
gzip on;
|
expires 1y;
|
||||||
gzip_min_length 1100;
|
add_header Cache-Control "public, immutable";
|
||||||
gzip_buffers 4 32k;
|
add_header Vary "Accept-Encoding";
|
||||||
gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml;
|
|
||||||
gzip_vary on;
|
|
||||||
gzip_comp_level 6;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# Include custom nginx configurations
|
||||||
include {{ $.DOKKU_ROOT }}/{{ $.APP }}/nginx.conf.d/*.conf;
|
include {{ $.DOKKU_ROOT }}/{{ $.APP }}/nginx.conf.d/*.conf;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user