Introduction

DDoS (Distributed Denial of Service) attacks can take your application down in seconds. I have been through it: a coordinated attack consumed memory, froze the proxy and left the infrastructure unavailable. The difference between losing SSH access and recovering in minutes lies in 6 specific prevention measures that I show in this article.

This tutorial covers the techniques I have proven in production: from configuring Cloudflare correctly to tuning the Linux kernel to withstand millions of requests. You will learn how to implement each of them with practical examples, without vague theory.

Comparison: server under DDoS without protection versus infrastructure protected by the 6 measures

⚠️ Warning: This article is based on a real DDoS incident. The measures described here are preventive. If you are under active attack, use this checklist in parallel with support from your CDN provider (Cloudflare, Akamai, etc.).

Prerequisites

To implement the measures in this article, you need:

  • Root or sudo access to the VPS/server
  • Docker and Docker Compose installed
  • Basic Linux knowledge (editing files, kernel commands)
  • A Cloudflare account configured as reverse proxy/CDN
  • A reverse proxy in production (Traefik, Nginx, HAProxy)
  • Monitoring tools (Prometheus, Grafana, or similar)

If you don’t have a reverse proxy in production yet, start with Traefik em Docker (Portuguese) or Nginx.

1. Disable Proxy Auto-Update in Production

New proxy versions (Traefik, Nginx) can contain bugs that only show up under high load. I learned it the hard way: an automatic Traefik update to a minor version introduced a memory leak that tripled RAM consumption during an attack.

The problem: if the proxy goes down under DDoS, the attacker has already won.

Implementation in Docker Compose

Freeze your proxy version and review updates manually before applying them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
version: '3.9'

services:
  traefik:
    image: traefik:v3.0.0  # ❌ DO NOT use 'latest' or 'v3'
    # Use a specific version (major.minor.patch)
    restart: unless-stopped
    environment:
      - TRAEFIK_LOG_LEVEL=WARN
      - TRAEFIK_ACCESSLOG=true
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik-config.yaml:/etc/traefik/traefik.yaml:ro
    networks:
      - frontend

  app:
    image: seu-app:1.2.3  # Pin your application too
    restart: unless-stopped

Safe Update Process

  1. Review the changelog before updating
  2. Test in staging with real traffic
  3. Apply during low-traffic hours
  4. Have a rollback ready: docker-compose up with the previous image
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Test the new version without replacing production
docker pull traefik:v3.1.0
docker run --rm traefik:v3.1.0 version

# If it passed the tests, update the compose file
# sed -i 's/traefik:v3.0.0/traefik:v3.1.0/g' docker-compose.yml

# Controlled deploy
docker-compose down
docker-compose up -d
docker-compose logs -f traefik  # Watch for 5 minutes

ℹ️ Info: Traefik v3.0.0 to v3.2.x received security patches. If you are on v2.10.x, update only if you have tested in staging. Old versions have CVEs, but rushed updates under attack cause failures.

2. Enable “Under Attack Mode” on Cloudflare

Cloudflare offers a mode specifically for DDoS: Under Attack Mode. It raises the challenge level (CAPTCHAs, browser validation) to block bots while letting legitimate users through.

Manual Configuration in the Cloudflare Dashboard

Follow these steps in the Cloudflare dashboard:

  1. Log in to the Cloudflare dashboard
  2. Select the site you want to configure
  3. Click Security in the side menu
  4. Click DDoS Protection
  5. Find the Managed DDoS Protection section
  6. Click Configure next to Under Attack Mode

The transition is immediate. Legitimate users get a 5-10 second challenge; automated bots tend to be blocked.

If “Under Attack” Does Not Appear in Your Dashboard

On some plans/accounts, the toggle may not be visible in the expected place. In that case, apply a temporary global challenge:

  1. Go to Security → WAF → Custom Rules
  2. Create a rule with the expression true
  3. Set the action to Managed Challenge (or JS Challenge, if you prefer)
  4. Place the rule at the top and publish it

This is not identical to “Under Attack”, but it delivers fast mitigation during an incident, with a similar effect in blocking massive automated traffic.

Automation: Enable via API

If you want to enable the mode automatically when anomalies are detected, use the Cloudflare API:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/bin/bash
# Script: enable-under-attack.sh

ZONE_ID="seu-zone-id"  # Find it in Domain → Overview → Zone ID
API_KEY="sua-api-key"  # Create it in My Profile → API Tokens
EMAIL="[email protected]"

# Enable Under Attack Mode
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/settings/security_level" \
  -H "X-Auth-Email: $EMAIL" \
  -H "X-Auth-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  --data '{"value":"under_attack"}'

echo "Under Attack Mode ativado"

Integration with Monitoring

Automatic trigger when the request rate exceeds 10,000/min:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Pseudocode for a Prometheus Alert
groups:
  - name: DDoS Detection
    rules:
      - alert: UnderDDoSAttack
        expr: rate(http_requests_total[1m]) > 10000
        for: 1m
        annotations:
          summary: "Ativando Under Attack Mode"
        actions:
          - webhook: "http://localhost:5000/enable-under-attack"

ℹ️ Info: “Under Attack Mode” blocks ~80% of automated bots, reducing security false positives. The cost is extra latency for legitimate users (5-10s), acceptable in a crisis.

3. Change the Server’s Real IP Address

If the attacker discovered your VPS’s real IP (through historical DNS records, whois, or social engineering), they can bypass Cloudflare and attack directly.

Scenario: the attacker runs WHOIS on the domain, finds an old IP, and sends requests straight to it, bypassing Cloudflare.

Steps to Change the IP

  1. Reserve a new IP with your VPS provider

    • On Hetzner, DigitalOcean, or Hostinger, this is free and takes 5 minutes
    • You can have multiple IPs per VPS
  2. Configure the new IP on the server

1
2
3
4
5
6
7
8
# List current IPs
ip addr show

# Add a new IP (example on Ubuntu/Debian)
sudo ip addr add 203.0.113.50/24 dev eth0

# To persist after reboot, edit /etc/netplan/ or /etc/network/interfaces
sudo nano /etc/netplan/01-netcfg.yaml

Example of /etc/netplan/01-netcfg.yaml:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
network:
  version: 2
  ethernets:
    eth0:
      addresses:
        - 198.51.100.10/24
        - 203.0.113.50/24  # New IP
      gateway4: 198.51.100.1
      nameservers:
        addresses: [8.8.8.8, 8.8.4.4]
  1. Update DNS to point to the new IP only within your internal infrastructure

    • Cloudflare keeps pointing to the previous IP (or to one you control)
    • Internal DNS points to the new IP
    • Change /etc/hosts on internal servers if needed
  2. Keep the old IP “trapped” in Cloudflare, pointing to a generic block

1
2
3
# No Cloudflare DNS:
example.com  → CNAME → proxy.example.com (Cloudflare)
old-ip-server → (não existe, ou aponta para black hole)

Validate the IP Change

1
2
3
4
5
6
# Confirm the new IP is active
curl -I http://203.0.113.50

# Test from outside with traceroute
traceroute example.com  # Should go through Cloudflare
traceroute 203.0.113.50  # Your server is isolated

⚠️ Warning: Changing the IP is disruptive. Have a rollback plan. If you use HTTPS pinning or IP-specific certificates, update them as well.

4. Configure File Descriptor Limits in Docker and Podman

Every open TCP connection consumes a file descriptor (FD). Under DDoS, thousands of connections stay pending, exhausting the system quota and freezing the application.

Symptom: “Too many open files” or SSH timeouts during an attack.

Understanding File Descriptors

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# See the current limit
ulimit -n
# Typical output: 1024

# See the hard limit (maximum)
ulimit -Hn
# Typical output: 65536

# See how many FDs are in use
lsof | wc -l

Configuration in Docker Compose

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
version: '3.9'

services:
  traefik:
    image: traefik:v3.0.0
    restart: unless-stopped
    ulimits:
      nofile:
        soft: 65000  # For normal applications
        hard: 65536  # System maximum
    # Alternative (short notation, not recommended)
    # ulimits: 65000:65536
    networks:
      - frontend

  app:
    image: seu-app:1.2.3
    ulimits:
      nofile:
        soft: 32000  # Less aggressive for the app
        hard: 65536

If you use Nginx instead of Traefik, the configuration looks like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
version: '3.9'

services:
  nginx:
    image: nginx:1.27-alpine
    restart: unless-stopped
    ulimits:
      nofile:
        soft: 65000
        hard: 65536
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro

  app:
    image: seu-app:1.2.3
    ulimits:
      nofile:
        soft: 32000
        hard: 65536

Configuration in Podman

In Podman, you can apply the same limit with --ulimit:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# Example with Nginx
podman run -d --name nginx \
  --ulimit nofile=65000:65536 \
  -p 80:80 -p 443:443 \
  nginx:1.27-alpine

# Example with Traefik
podman run -d --name traefik \
  --ulimit nofile=65000:65536 \
  -p 80:80 -p 443:443 \
  traefik:v3.0.0

If you use podman-compose, keep the ulimits key in the YAML, just like in Docker Compose.

Raise It Globally on the Host

If multiple containers need high limits:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Edit /etc/security/limits.conf
sudo nano /etc/security/limits.conf

# Add:
# *               soft    nofile          65000
# *               hard    nofile          65536
# root            soft    nofile          65536
# root            hard    nofile          65536

# Reload
sudo sysctl -p

# Verify
ulimit -n

Stress Test

Simulate pending connections to validate the limit:

1
2
3
4
5
# Use ab (Apache Bench) or hey
ab -n 100000 -c 10000 http://127.0.0.1:80/

# Monitor FDs in real time (adjust the process: traefik or nginx)
watch -n 1 'lsof | grep -E "traefik|nginx" | wc -l'

ℹ️ Info: A limit of 65,000 file descriptors allows ~60,000 simultaneous connections (accounting for FDs used by logs, internal sockets, etc.). In practice, set it to 80-90% of the hard limit.

5. Enable TCP Cookies in the Kernel

TCP SYN Flood is a simple attack: the attacker sends SYN packets (the start of a TCP connection) without answering the SYN-ACK, causing the server to allocate memory for incomplete connections (SYN backlog).

TCP Syncookies solves this without accepting the connection: the server encodes information in the SYN-ACK so that memory is only allocated AFTER the client is validated.

Enable It on Linux

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# Check the current status
sysctl net.ipv4.tcp_syncookies
# Output: net.ipv4.tcp_syncookies = 0  (disabled) or = 1 (enabled)

# Enable immediately
sudo sysctl -w net.ipv4.tcp_syncookies=1

# Persist after reboot
echo "net.ipv4.tcp_syncookies = 1" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

Complementary Settings (kernel hardening)

While you are at it, enable other protections:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# Drop SYN packets with an invalid IP
echo "net.ipv4.tcp_syncookies = 1" | sudo tee -a /etc/sysctl.conf

# Limit the SYN backlog (incomplete connections)
echo "net.ipv4.tcp_max_syn_backlog = 4096" | sudo tee -a /etc/sysctl.conf

# Increase the listen backlog size (applications that accept many connections)
echo "net.core.somaxconn = 4096" | sudo tee -a /etc/sysctl.conf

# Protection against IP spoofing (reverse path filter)
echo "net.ipv4.conf.all.rp_filter = 1" | sudo tee -a /etc/sysctl.conf

# Reload
sudo sysctl -p

Validate the Configuration

1
2
3
4
5
# Check whether TCP Syncookies is working
sudo cat /proc/net/netstat | grep -i sync

# Expected output (with syncookies active):
# TcpExt: SyncookiesSent SyncookiesRecv SyncookiesFailed ...

📝 Example: In a typical DDoS with 500,000 SYN/second, without syncookies the server allocates 5 GB of memory in seconds. With syncookies enabled, consumption stays < 100 MB.

6. Implement Proper Monitoring with Alerts

Monitoring is prevention. If you detect anomalies (request spikes, abnormal memory consumption) within 1 minute, you can activate defenses before losing SSH.

Critical Metrics for DDoS

Monitor these 5 metrics with real-time alerts:

MetricAlertAction
Request rate/min> 10,000Enable Under Attack Mode
Pending TCP connections> 50,000Increase tcp_max_syn_backlog
Memory consumption (proxy)> 80%Restart container, enable Under Attack
Accumulated processes (zombie)> 100Investigate leak, restart app
P99 latency> 5sSign of a bottleneck or slow attack

Configuration with Prometheus + Alertmanager

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# prometheus.yml
global:
  scrape_interval: 15s

scrape_configs:
  - job_name: 'traefik'
    static_configs:
      - targets: ['localhost:8080']  # Traefik metrics

  - job_name: 'node'
    static_configs:
      - targets: ['localhost:9100']  # Node Exporter (host metrics)

# File: alert_rules.yml
groups:
  - name: ddos_alerts
    interval: 30s
    rules:
      - alert: HighRequestRate
        expr: rate(http_requests_total[1m]) > 10000
        for: 1m
        labels:
          severity: critical
        annotations:
          summary: "Taxa alta de requisições: {{ $value }} req/s"
          description: "Possível DDoS. Ativar Under Attack Mode no Cloudflare."

      - alert: HighTCPConnections
        expr: node_sockstat_TCP_inuse > 50000
        for: 2m
        labels:
          severity: warning
        annotations:
          summary: "{{ $value }} conexões TCP pendentes"

      - alert: HighMemoryUsage
        expr: container_memory_usage_bytes{name="traefik"} / 1073741824 > 0.8
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "Memória do Traefik em {{ $value }}%"

Simple Monitoring Script (without Prometheus)

If you don’t have a monitoring stack installed, use this bash script:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
# File: ddos-monitor.sh

THRESHOLD_REQUESTS=10000
THRESHOLD_MEMORY=80
THRESHOLD_TCP=50000

while true; do
  # Request rate (Traefik logs)
  REQ_RATE=$(tail -10000 /var/log/traefik/access.log | wc -l)
  
  # Traefik memory consumption
  MEM_USAGE=$(docker stats traefik --no-stream --format "{{.MemPerc}}" | sed 's/%//')
  
  # TCP connections
  TCP_CONNS=$(netstat -an | grep ESTABLISHED | wc -l)

  echo "[$(date '+%Y-%m-%d %H:%M:%S')] Req/min: $REQ_RATE | Mem: ${MEM_USAGE}% | TCP: $TCP_CONNS"

  if (( $(echo "$REQ_RATE > $THRESHOLD_REQUESTS" | bc -l) )); then
    echo "⚠️ ALERTA: Taxa de requisições alta!"
    # Call a webhook or send a notification
    curl -X POST http://alertmanager:9093/api/v1/alerts \
      -H "Content-Type: application/json" \
      --data '{"alerts":[{"labels":{"alertname":"HighRequestRate"}}]}'
  fi

  sleep 60
done

Run it in the background:

1
nohup ./ddos-monitor.sh > ddos-monitor.log 2>&1 &

📝 Example: A client of mine detected a DDoS in 2 minutes thanks to alerts. They enabled Under Attack Mode and increased file descriptors. The site stayed online with acceptable latency. Without alerts, the downtime would have lasted hours.

7. Practical Example: Complete Production Configuration

Here is a complete Docker Compose configuration with all measures applied:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
version: '3.9'

services:
  traefik:
    image: traefik:v3.0.0  # Pinned version, no auto-update
    container_name: traefik
    restart: unless-stopped
    
    # High file descriptors
    ulimits:
      nofile:
        soft: 65000
        hard: 65536
    
    environment:
      # Logs for monitoring
      - TRAEFIK_LOG_LEVEL=WARN
      - TRAEFIK_ACCESSLOG=true
      - TRAEFIK_ACCESSLOG_FILEPATH=/var/log/traefik/access.log
      - TRAEFIK_ACCESSLOG_FORMAT=json
      
      # Metrics
      - TRAEFIK_METRICS_PROMETHEUS=true
      - TRAEFIK_METRICS_PROMETHEUS_ADDENTRYPOINTSLABELS=true
    
    ports:
      - "80:80"
      - "443:443"
      - "8080:8080"  # Dashboard (protect it with auth)
    
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro
      - ./traefik-config.yaml:/etc/traefik/traefik.yaml:ro
      - ./certs:/certs:ro
      - /var/log/traefik:/var/log/traefik
    
    networks:
      - frontend

  app:
    image: seu-app:1.2.3  # Pinned version
    container_name: app
    restart: unless-stopped
    
    ulimits:
      nofile:
        soft: 32000
        hard: 65536
    
    environment:
      - ENVIRONMENT=production
    
    labels:
      # Traefik auto-discovery
      - "traefik.enable=true"
      - "traefik.http.routers.app.rule=Host(`example.com`)"
      - "traefik.http.services.app.loadbalancer.server.port=3000"
    
    networks:
      - frontend

networks:
  frontend:
    driver: bridge

The traefik-config.yaml file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
global:
  checkNewVersion: false  # Do not check for updates
  sendAnonymousUsage: false

entryPoints:
  web:
    address: ":80"
    http:
      maxRequestBodyBytes: 2500000  # Limit payload (anti-upload bomb)
  websecure:
    address: ":443"
    http:
      maxRequestBodyBytes: 2500000

api:
  insecure: false  # Protect the dashboard
  dashboard: true

log:
  level: WARN

accessLog: {}

metrics:
  prometheus:
    entryPoint: metrics
    service: prometheus

providers:
  docker:
    endpoint: "unix:///var/run/docker.sock"
    exposedByDefault: false
    watch: true

If you use Nginx instead of Traefik, here is an equivalent production example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
version: '3.9'

services:
  nginx:
    image: nginx:1.27-alpine  # Pinned version, no auto-update
    container_name: nginx
    restart: unless-stopped

    ulimits:
      nofile:
        soft: 65000
        hard: 65536

    ports:
      - "80:80"
      - "443:443"

    volumes:
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./certs:/etc/nginx/certs:ro
      - /var/log/nginx:/var/log/nginx

    networks:
      - frontend

  app:
    image: seu-app:1.2.3
    container_name: app
    restart: unless-stopped

    ulimits:
      nofile:
        soft: 32000
        hard: 65536

    environment:
      - ENVIRONMENT=production

    expose:
      - "3000"

    networks:
      - frontend

networks:
  frontend:
    driver: bridge

The nginx/nginx.conf file (baseline for high connection volume):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
user nginx;
worker_processes auto;
pid /var/run/nginx.pid;

events {
  worker_connections 8192;
  use epoll;
  multi_accept on;
}

http {
  sendfile on;
  tcp_nopush on;
  tcp_nodelay on;
  keepalive_timeout 30;
  keepalive_requests 1000;
  types_hash_max_size 2048;
  server_tokens off;

  # Limits to reduce the impact of a basic flood
  client_max_body_size 2m;
  client_body_timeout 10s;
  client_header_timeout 10s;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /var/log/nginx/access.log main;
  error_log /var/log/nginx/error.log warn;

  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  upstream app_backend {
    server app:3000;
    keepalive 64;
  }

  server {
    listen 80;
    server_name _;

    location / {
      proxy_http_version 1.1;
      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 Connection "";
      proxy_pass http://app_backend;
    }
  }
}

Tips and Good Practices

  • 1. Rate Limiting on Cloudflare: Set a limit of 100 requests/IP/minute. This automatically blocks aggressive bots before they reach your server.

  • 2. Keep Traffic Logs: Archive access logs in JSON for post-attack analysis. Identify patterns (source IP, target endpoint, user-agent) to refine future rules.

  • 3. Test Your Defenses Regularly: Once a month, simulate a light DDoS (with a tool like locust or ab) and validate that alerts work. Finding gaps in production is expensive.

  • 4. Geographic Redundancy: If possible, distribute your app across multiple datacenters. A single DDoS won’t take everything down. Cloudflare offers geographic load balancing.

  • 5. Communication with Your Provider: If you hire premium support (Cloudflare Pro/Business), tell them about your mitigation plan. They can enable extra protections faster.

Objective Summary

  • TCP Syncookies — enable it in the kernel with sysctl net.ipv4.tcp_syncookies=1 to block SYN Flood without allocating memory indiscriminately.

  • File Descriptors in Docker — set ulimits.nofile.soft: 65000 in docker-compose.yml to accept up to 60,000 simultaneous connections during an attack.

  • Under Attack Mode (Cloudflare) — enable it manually under Security → Overview or via API to force CAPTCHAs on bots, blocking ~80% of malicious traffic.

  • Pinned Proxy Version — use image: traefik:v3.0.0 instead of latest to prevent bugs introduced by automatic updates from taking the application down under load.

  • New IP Address — add a secondary IP to the VPS and use it exclusively internally, leaving the old one “trapped” in Cloudflare to isolate it from the attacker.

  • Monitoring with Alerts — track request rate, TCP connections, memory and processes with Prometheus or a simple bash script; the critical threshold is > 10,000 req/min or > 50,000 TCP connections.

Read Also

References