Self-Hosting Next.js on a VPS

A VPS gives you a real Linux machine you control: install the runtime, run the app as a service, and put a web server in front of it. That control is useful, but it also means you own updates, TLS, logs, backups, and recovery. The goal is a small stack with clear boundaries so each part has one job.
Choose the shape of the deployment
For one app on one modest server, a Node.js process managed bysystemd behind Nginx is a good starting point. Next.js runs its own production server; Nginx handles public traffic, TLS, request limits, and proxying. Keep Next.js bound to loopback so port 3000 is never directly reachable from the internet.
| Shape | Good fit | Trade-off |
|---|---|---|
| Node + systemd | One app, one server, simplest operations | Host packages and app releases need care |
| Docker Compose | A repeatable app plus supporting services | More moving parts and image maintenance |
| Static export | Pages that need no server rendering | Server features such as Server Actions are unavailable |
Prepare the server
Provision a supported Linux distribution, attach a domain, and create a non-root account for deployments. Start by applying security updates and installing only the packages you need. On a fresh Ubuntu host, the outline looks like this:
sudo apt update && sudo apt upgrade -ysudo apt install -y nginx ufw ca-certificates
# Create a dedicated, unprivileged account for the app.sudo adduser --system --group --home /srv/my-next-app nextjssudo install -d -o nextjs -g nextjs /srv/my-next-app/releasessudo install -d -o nextjs -g nextjs /srv/my-next-app/shared
# Allow SSH before enabling the firewall; keep your current SSH session open.sudo ufw allow OpenSSHsudo ufw allow 'Nginx Full'sudo ufw enablesudo ufw status verboseAllow SSH and web traffic in both the host firewall and the VPS provider's network firewall. Confirm SSH access before enabling firewall rules, and keep a recovery console available. Install an active Node.js LTS version supported by your app and package manager; avoid relying on an old distribution default. Pin the runtime version so local, CI, and server builds agree. For example, compare node --versionand the package manager version on each machine before promoting a release.
Build for production
Use the package manager and lockfile already committed by the project. A production deployment installs locked dependencies, builds once, and starts the production server. The standard scripts are small and explicit:
{ "scripts": { "dev": "next dev", "build": "next build", "start": "next start" }}Run next build in CI or on the server, never next dev as the public process. Ensure the deployment target has the same Node major version, native libraries, and environment inputs used for the build. Keep secrets out of NEXT_PUBLIC_*variables: those values are bundled for the browser.
DATABASE_URL=postgresql://app_user:replace-me@db.internal:5432/appAUTH_SECRET=replace-with-a-long-random-secretNEXT_PUBLIC_SITE_URL=https://example.comPut the actual runtime secrets in a server-owned file with restrictive permissions, or inject them from your deployment system. Do not commit the file, bake production secrets into a container image, or print them in CI logs. If the app uses native Node dependencies, build on the target architecture or in a matching Linux build image.
Run Next.js reliably
A shell session is not a process manager: the app would stop when the session ends and would not return after a reboot.systemd starts the service on boot, restarts it after failures, and collects its standard output in the journal. Create an environment file readable only by the service account, then define a unit like this:
[Unit]Description=Next.js web applicationAfter=network.target
[Service]Type=simpleUser=nextjsGroup=nextjsWorkingDirectory=/srv/my-next-app/currentEnvironmentFile=/etc/my-next-app/production.envEnvironment=NODE_ENV=productionEnvironment=HOSTNAME=127.0.0.1Environment=PORT=3000ExecStart=/usr/bin/node /srv/my-next-app/current/node_modules/next/dist/bin/next start --hostname 127.0.0.1 --port 3000Restart=on-failureRestartSec=5TimeoutStopSec=30KillSignal=SIGTERMNoNewPrivileges=truePrivateTmp=trueProtectHome=true
[Install]WantedBy=multi-user.targetThe Node executable path can differ by installation method; usecommand -v node and updateExecStart to match. The app directory should be owned by the deploy account, while the environment file stays root-owned and readable by the service group. Give the app write access only to explicit persistent directories.
sudo chown root:nextjs /etc/my-next-app/production.envsudo chmod 640 /etc/my-next-app/production.env
sudo systemctl daemon-reloadsudo systemctl enable --now my-next-appsudo systemctl status my-next-appsudo journalctl -u my-next-app -fRestart the service after changing its unit or environment file. Prefer graceful SIGTERM shutdown and allow enough stop time for in-flight requests to finish. Do not run two processes on the same port; for planned zero-downtime releases, use two ports behind a health-checked proxy or a deployment platform that supports rolling replacement.
Put Nginx in front
Nginx accepts public connections and forwards requests to the private Next.js listener. Forward the original host and scheme so redirects and secure cookies see the public URL. Themap belongs in Nginx'shttp context; the server block belongs in a site configuration included from that context.
# Place inside the http { } block, for example in# /etc/nginx/conf.d/websocket-map.conf.map $http_upgrade $connection_upgrade { default upgrade; '' close;}server { listen 80; listen [::]:80; server_name example.com www.example.com;
location / { proxy_pass http://127.0.0.1:3000; 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 Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade;
# Preserve streaming responses from the App Router. proxy_buffering off; proxy_read_timeout 60s; }}Enable the site, check the configuration, and reload Nginx only after validation. This initial site is an HTTP proxy, so it works before certificate files exist. Once DNS resolves to the VPS, Certbot's Nginx plugin can obtain a certificate and add the HTTPS listener and redirect.
sudo ln -s /etc/nginx/sites-available/my-next-app /etc/nginx/sites-enabled/my-next-appsudo nginx -tsudo systemctl reload nginx
# After installing Certbot and its Nginx plugin for your distribution:sudo certbot --nginx --redirect -d example.com -d www.example.comsudo certbot renew --dry-runKeep Nginx buffering disabled when the app depends on streaming responses. If you add a CDN or load balancer later, verify that every hop preserves streaming and forwards trusted proxy headers. Set body-size and timeout limits to match the application instead of leaving generous defaults everywhere.
Release without surprises
A release should be a known build, not a set of edits made directly inside the live directory. Build from a clean checkout, record the commit and runtime version, and copy the required output into a new versioned directory. Keep shared state such as uploads and environment files outside that directory.
# On the build machine or deployment runnerpnpm install --frozen-lockfilepnpm build
# Copy the complete runtime needed by this app to a new release directory.# Keep the environment file outside the release and never copy .env into Git.rsync -a --delete --exclude=.git --exclude='.env' --exclude='.env.*' --exclude=.next/cache ./ deploy@server:/srv/my-next-app/releases/2026-11-22-1200/
# On the server, set release ownership and point the current symlink at it.sudo chown -R nextjs:nextjs /srv/my-next-app/releases/2026-11-22-1200ln -sfn /srv/my-next-app/releases/2026-11-22-1200 /srv/my-next-app/currentsudo systemctl restart my-next-appsudo systemctl --no-pager --full status my-next-appTreat this snippet as a deployment outline: it assumes the target release directory already exists and that the copied files include the build output, package manifest, lockfile, and production dependencies. If a database schema changes, run a backward-compatible migration as a deliberate release step before switching traffic. Keep the previous release available so rollback means switching the symlink back and restarting.
Avoid running npm install against the live directory while requests are being served. Never use--force or disable lockfile checks as an automatic fix for a failed deployment; resolve the dependency mismatch in the source branch and rebuild.
Keep the server healthy
A deployment is finished only when you can tell whether it is serving correctly and recover when it is not. Confirm the app responds locally and through the public hostname, then inspect the service and proxy logs. Add an application health endpoint if your monitoring needs a reliable readiness signal.
curl --fail --show-error --head http://127.0.0.1:3000/curl --fail --show-error --head https://example.com/sudo systemctl --no-pager --full status my-next-appsudo journalctl -u my-next-app --since "15 minutes ago" --no-pagersudo tail -n 100 /var/log/nginx/error.logPatch the operating system and Node runtime on a regular schedule. Keep SSH key-based, disable password login after confirming key access, and restrict administrative access. Use provider snapshots or off-server backups for databases and uploaded files; a snapshot on the same disk is not a backup. Test restoration before you need it.
Watch memory, disk space, CPU, restart counts, and response errors. A small VPS can run out of memory during a production build, so building in CI and transferring the artifact often makes deployment more predictable. Set log retention so journal and proxy logs cannot fill the disk unnoticed.
Know when to scale
One VPS is a useful first production setup, not an architecture that must last forever. Scale when measurements show a limit: CPU-bound rendering, memory pressure, slow database queries, or traffic that a single process cannot serve comfortably. First profile the app and database; then add capacity where the bottleneck actually is.
Multiple Next.js instances introduce coordination work. Build the same artifact for every instance, share cache storage when the app needs consistent caching, coordinate tag invalidation, and use the same Server Actions encryption key across instances when required. Configure a deployment ID for rolling deployments so clients can recover cleanly from version skew. Put uploads and session state in shared services, not instance-local memory or disk.
A practical progression
- Measure the app and database before changing topology.
- Move builds to CI and make releases reproducible.
- Externalize uploads, sessions, and shared cache as needed.
- Add a second instance behind a load balancer with health checks.
- Test deploy, rollback, backup, and restore procedures.
Resources
Use the current framework and runtime documentation when choosing versions or turning on advanced features; self-hosted behavior can change between major releases.
- Next.js self-hosting guide — reverse proxies, caching, streaming, and multiple instances.
- Next.js deployment guide — Node.js server, Docker, and static export options.
- Node.js release schedule — select an actively supported LTS line.
- Nginx proxy module reference — proxy headers, buffering, and connection behavior.