Zum Hauptinhalt springen
Zurück zur Kategorie

Next.js und React Deploy: Produktion auf VPS

Anleitung zum Deployen von Next.js und React-Anwendungen auf einem VPS. Node.js-Setup, Next.js Build und Start, PM2 Process Manager, Nginx Reverse Proxy, Umgebungsvariablen und CI/CD-Grundlagen.

Lesezeit: 16 min Web Hosting / Anwendungen
nextjsreactnodejspm2nginxdeployvpsjavascriptci-cd
Autor
REXE Teknoloji Network & Security Team
Redaktion
REXE Teknoloji Technical Editorial
Erstveröffentlichung
Letzte Aktualisierung

Next.js und React Deploy: Produktionsumgebung auf VPS

Next.js ist das beliebteste Framework für moderne React-basierte Webanwendungen. Next.js auf dem eigenen VPS statt auf Plattformen wie Vercel zu betreiben bietet Kosteneinsparungen, volle Kontrolle und Anpassungsmöglichkeiten. Diese Anleitung führt Sie Schritt für Schritt durch das Deployen einer Next.js-Anwendung auf einem VPS.

Node.js Installation (mit nvm)

hljs bash
# nvm installieren
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc

# LTS-Version installieren
nvm install --lts
nvm use --lts
nvm alias default node

node --version
npm --version

Anwendung auf den Server übertragen

hljs bash
sudo mkdir -p /var/www/mynextapp
sudo chown $USER:$USER /var/www/mynextapp
cd /var/www
git clone https://github.com/benutzer/mynextapp.git
cd mynextapp
npm install

Umgebungsvariablen

hljs env
NODE_ENV=production
NEXT_PUBLIC_API_URL=https://api.example.com
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
NEXTAUTH_SECRET=ihr-geheimer-schluessel
NEXTAUTH_URL=https://example.com

Variablen mit dem Präfix NEXT_PUBLIC_ sind im Browser sichtbar. Verwenden Sie dieses Präfix nicht für sensible Informationen.

Next.js Build und Standalone-Ausgabe

hljs javascript
// next.config.js
const nextConfig = {
  output: 'standalone',
  images: {
    domains: ['example.com'],
  },
};

module.exports = nextConfig;
hljs bash
# Produktions-Build erstellen
npm run build

Prozessverwaltung mit PM2

hljs javascript
// ecosystem.config.js
module.exports = {
  apps: [
    {
      name: 'mynextapp',
      script: '.next/standalone/server.js',
      cwd: '/var/www/mynextapp',
      instances: 'max',
      exec_mode: 'cluster',
      env: {
        NODE_ENV: 'production',
        PORT: 3000,
        HOSTNAME: '0.0.0.0'
      },
      max_memory_restart: '1G',
      autorestart: true
    }
  ]
};
hljs bash
# Statische Dateien für Standalone-Build kopieren
cp -r .next/static .next/standalone/.next/static
cp -r public .next/standalone/public

# Anwendung starten
pm2 start ecosystem.config.js
pm2 startup
pm2 save

Nginx Reverse Proxy Konfiguration

hljs nginx
server {
    listen 80;
    server_name example.com www.example.com;

    location /_next/static/ {
        alias /var/www/mynextapp/.next/static/;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    location / {
        proxy_pass http://localhost:3000;
        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;
    }

    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    client_max_body_size 50M;
}
hljs bash
sudo ln -s /etc/nginx/sites-available/mynextapp /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

SSL-Zertifikat

hljs bash
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com

CI/CD Grundlagen (GitHub Actions)

hljs yaml
name: Deploy to VPS
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          script: |
            cd /var/www/mynextapp
            git pull origin main
            npm install
            npm run build
            cp -r .next/static .next/standalone/.next/static
            cp -r public .next/standalone/public
            pm2 reload mynextapp

Manueller Deployment-Workflow

hljs bash
cd /var/www/mynextapp
git pull origin main
npm install
npm run build
cp -r .next/static .next/standalone/.next/static
cp -r public .next/standalone/public
pm2 reload mynextapp

Auf REXE-Servern werden für Next.js mindestens 1 GB RAM empfohlen. Große Anwendungen benötigen möglicherweise 2 GB+ RAM während des Builds. Verwenden Sie den PM2-Cluster-Modus, um CPU-Kerne voll auszunutzen.

Fazit

Ihre Next.js-Anwendung läuft jetzt in einer Produktionsumgebung auf einem VPS, verwaltet von PM2, hinter einem Nginx Reverse Proxy und mit SSL gesichert. Richten Sie eine CI/CD-Pipeline mit GitHub Actions ein, um automatisches Deployment bei jedem Push zu ermöglichen.

Häufig gestellte Fragen

Ich erhalte einen 'out of memory'-Fehler beim Next.js-Build.

Erhöhen Sie das Node.js-Speicherlimit beim Build: 'NODE_OPTIONS="--max-old-space-size=4096" npm run build'. Stellen Sie sicher, dass Ihr Server mindestens 2 GB RAM hat. Die Verwendung von Standalone-Ausgabe in großen Projekten reduziert Build-Zeit und Speicherverbrauch.

Next.js Image Optimization funktioniert nicht.

Überprüfen Sie die Einstellung images.domains oder images.remotePatterns in next.config.js. Verifizieren Sie, dass der /_next/image/-Pfad in Nginx die korrekte Proxy-Konfiguration hat. Stellen Sie sicher, dass das sharp-Paket installiert ist: 'npm install sharp'.

API-Routen funktionieren nicht, ich erhalte 404-Fehler.

Stellen Sie sicher, dass der /api/-Pfad in Nginx zur Next.js-Anwendung proxyt. Bei Standalone-Build prüfen Sie, ob server.js korrekt läuft. Überprüfen Sie PM2-Logs mit 'pm2 logs mynextapp'.

Meine Next.js-Anwendung ist langsam, wie optimiere ich sie?

Verwenden Sie Standalone-Ausgabe (output: 'standalone' in next.config.js). Aktivieren Sie den PM2-Cluster-Modus. Fügen Sie langfristigen Cache für /_next/static/ in Nginx hinzu. Verwenden Sie next/image für Bildoptimierung. Identifizieren Sie große Pakete mit Bundle Analyzer.

Verwandte Artikel

Node.js App deployen: PM2 und Nginx Anleitung

Vollständige Anleitung zum Deployen von Node.js-Anwendungen auf einem VPS. Node.js-Installation mit nvm, PM2 Process Manager, Nginx Reverse Proxy, SSL-Zertifikat und Umgebungsvariablen.

15 min
nodejspm2nginx

PHP-App deployen: LAMP und LEMP Stack Anleitung

Vollständige Anleitung zum Deployen von PHP-Anwendungen auf einem VPS. LAMP vs LEMP Vergleich, Apache/Nginx + PHP-FPM + MySQL Setup, Virtual Host Konfiguration und PHP-Versionsverwaltung.

18 min
phplamplemp

WordPress Installation und Optimierung: VPS Anleitung

Anleitung zur Installation und Optimierung von WordPress auf einem VPS. LEMP Stack Setup, wp-config.php Einstellungen, Dateiberechtigungen, SSL, OPcache Performance-Optimierung und Sicherheitshärtung.

20 min
wordpressvpslemp
NetzwerkverkehrEingehend GbpsAusgehend Gbps