If you want to deploy Next.js on a VPS in the right way, this guide shows a full production setup. It uses the Next.js standalone output, a non-root Docker image, localhost binding, Nginx, and HTTPS. Also, it covers a cache that survives restarts, runtime vs. build-time variables, streaming, and a versioned rollback.
Everything in this guide uses a small App Router project. Replace it with your own app after you pass the tests.
Prerequisites
Before you start, make sure you have the items below:
- A Linux VPS with Ubuntu 24.04 LTS, root or sudo access, and at least 2 GB of RAM. A Linux VPS with NVMe storage is a good base for Docker builds.
- A domain name with an A record that points to your server IP.
- Docker Engine and the Docker Compose plugin.
You can install Docker, Nginx, and Certbot with the commands below:
sudo apt updatesudo apt install ca-certificates curl nginx certbot python3-certbot-nginx -ycurl -fsSL https://get.docker.com | sudo shsudo usermod -aG docker $USER
Log out and log in again. Then, check the installed version:
docker --versiondocker compose version
Step 1: Create the Project
You can create a new Next.js project with the App Router. It will be the small test app we deploy in the rest of this guide.
mkdir nextjs-vps && cd nextjs-vpsnpx create-next-app@latest app --ts --app --no-tailwind --no-src-dir --import-alias "@/*" --use-npmcd app
Pick the defaults if the tool asks more questions. Keep the package-lock.json file, because the Dockerfile needs it.
Step 2: Turn On Standalone Output and the Cache Handler
By default, Next.js keeps its cache on the local disk of the server. In a container, that disk is deleted when you replace the container. A small cache handler lets us write the cache to a folder we control.
Run these commands inside the app folder. First, delete next.config.ts if it exists:
Then, create the next.config.js file with the command below:
cat > next.config.js <<'EOF'module.exports = { output: "standalone", cacheHandler: require.resolve("./cache-handler.js"), cacheMaxMemorySize: 0, async headers() { return [ { source: "/:path*{/}?", headers: [{ key: "X-Accel-Buffering", value: "no" }], }, ]; },};EOF
output: "standalone" builds a small server with only the needed files.
cacheMaxMemorySize: 0 turns off the memory cache, so the disk holds the cache.
X-Accel-Buffering: no tells Nginx not to buffer responses, so streaming works.
Once you are done, check that the file exists:
Now create cache-handler.js. It saves each cache entry as a file inside a folder named after your app version:
cat > cache-handler.js <<'EOF'const fs = require("node:fs");const path = require("node:path");const crypto = require("node:crypto"); const DIR = path.join( process.env.CACHE_DIR || "/cache", process.env.APP_VERSION || "dev");fs.mkdirSync(DIR, { recursive: true }); const file = (key) => path.join(DIR, crypto.createHash("sha256").update(key).digest("hex") + ".json"); function replacer(k, v) { const raw = this[k]; if (raw instanceof Map) return { __type: "Map", data: [...raw] }; if (raw instanceof Uint8Array) return { __type: "Buf", data: Buffer.from(raw).toString("base64") }; return v;}function reviver(_k, v) { if (v && v.__type === "Map") return new Map(v.data); if (v && v.__type === "Buf") return Buffer.from(v.data, "base64"); return v;} module.exports = class FileCacheHandler { constructor(options) { this.options = options; } async get(key) { try { return JSON.parse(fs.readFileSync(file(key), "utf8"), reviver); } catch { return null; } } async set(key, data, ctx = {}) { const tags = [...(ctx.tags || [])]; const header = data && data.headers && data.headers["x-next-cache-tags"]; if (header) tags.push(...String(header).split(",")); const entry = { value: data, lastModified: Date.now(), tags }; const tmp = file(key) + ".tmp"; fs.writeFileSync(tmp, JSON.stringify(entry, replacer)); fs.renameSync(tmp, file(key)); } async revalidateTag(tags) { const list = [].concat(tags); for (const f of fs.readdirSync(DIR)) { if (!f.endsWith(".json")) continue; try { const p = path.join(DIR, f); const e = JSON.parse(fs.readFileSync(p, "utf8")); if ((e.tags || []).some((t) => list.includes(t))) fs.unlinkSync(p); } catch {} } } resetRequestCache() {}};EOF
Check that the file exists with the commands below:
ls -l cache-handler.jsnode --check cache-handler.js
node --check only tests the syntax. It prints nothing if the file is fine.
Note: Outside Docker, the handler may fail with a permission error because /cache does not exist. Build through Docker (Step 5), or run export CACHE_DIR=/tmp/cache first if you build on the host.
Step 3: Add the Test Pages
In this step, you can add three small test pages. One tests the ISR cache, one shows runtime and build-time variables, and one tests streaming. You will use them in Step 8 to check that everything works. Create the folders with:
mkdir -p app/env app/stream
For the ISR page, which replaces the default app/page.tsx, run:
cat > app/page.tsx <<'EOF'export const revalidate = 60; export default function Home() { return ( <main> <h1>Next.js on a VPS</h1> <p>Version: {process.env.APP_VERSION ?? "unknown"}</p> <p>Generated at: {new Date().toISOString()}</p> </main> );}EOF
For the Env page, which shows runtime and build-time variables:
cat > app/env/page.tsx <<'EOF'import { connection } from "next/server"; export default async function EnvPage() { await connection(); return ( <main> <p>Runtime: {process.env.RUNTIME_MESSAGE ?? "not set"}</p> <p>Build time: {process.env.NEXT_PUBLIC_BUILD_LABEL ?? "not set"}</p> </main> );}EOF
For the Streaming page, run:
cat > app/stream/page.tsx <<'EOF'import { Suspense } from "react";import { connection } from "next/server"; async function Slow() { await connection(); await new Promise((r) => setTimeout(r, 3000)); return <p>Slow part loaded after 3 seconds.</p>;} export default function StreamPage() { return ( <main> <p>This part shows right away.</p> <Suspense fallback={<p>Loading the slow part...</p>}> <Slow /> </Suspense> </main> );}EOF
Step 4: Create the Dockerfile
In this step, you must write the Dockerfile. It builds the app in three stages and runs it as the non-root node user. This keeps the final image small and safer. Create the Dockerfile with:
cat > Dockerfile <<'EOF'ARG NODE_VERSION=24-slim FROM node:${NODE_VERSION} AS depsWORKDIR /appCOPY package.json package-lock.json ./RUN npm ci --no-audit --no-fund FROM node:${NODE_VERSION} AS builderWORKDIR /appCOPY --from=deps /app/node_modules ./node_modulesCOPY . .ARG NEXT_PUBLIC_BUILD_LABEL=defaultENV NEXT_PUBLIC_BUILD_LABEL=$NEXT_PUBLIC_BUILD_LABELENV NODE_ENV=productionRUN npm run build FROM node:${NODE_VERSION} AS runnerWORKDIR /appENV NODE_ENV=productionENV PORT=3000ENV HOSTNAME=0.0.0.0ENV CACHE_DIR=/cacheCOPY --from=builder --chown=node:node /app/public ./publicCOPY --from=builder --chown=node:node /app/.next/standalone ./COPY --from=builder --chown=node:node /app/.next/static ./.next/staticCOPY --chown=node:node cache-handler.js ./cache-handler.jsRUN mkdir /cache && chown node:node /cacheUSER nodeEXPOSE 3000CMD ["node", "server.js"]EOF
Then, create the .dockerignore file with the command below:
cat > .dockerignore <<'EOF'node_modules.next.gitEOF
Note: HOSTNAME=0.0.0.0 is needed inside the container so Docker can reach the app. The host side is locked to localhost in the next step.
Step 5: Create the Compose File
At this point, you can must create the Compose file. It builds the image, binds the app to localhost only, and mounts a volume for the cache. Run the command below to create the Compose file:
cat > compose.yaml <<'EOF'services: web: image: nextjs-vps:${APP_VERSION:-v1} build: context: . args: NEXT_PUBLIC_BUILD_LABEL: ${NEXT_PUBLIC_BUILD_LABEL:-default} restart: unless-stopped ports: - "127.0.0.1:3000:3000" environment: APP_VERSION: ${APP_VERSION:-v1} RUNTIME_MESSAGE: ${RUNTIME_MESSAGE:-hello} volumes: - next_cache:/cache volumes: next_cache:EOF
The port line 127.0.0.1:3000:3000 keeps the app off the public internet, so only Nginx can reach it. Also, Docker skips UFW rules for published ports, so binding to localhost is safer than trusting the firewall.
Then, build and start version 1 with the command below:
APP_VERSION=v1 NEXT_PUBLIC_BUILD_LABEL=build-one RUNTIME_MESSAGE=hello docker compose up -d --build
Check that the container is running with the commands below:
docker compose pscurl -I http://127.0.0.1:3000
You should see HTTP/1.1 200 OK.
Step 6: Set Up Nginx Reverse Proxy
Now you can configure Nginx as a reverse proxy. It receives web traffic on port 80 and passes it to your app on 127.0.0.1:3000.
Replace app.example.com with your own domain in every command below. Create the Nginx config file:
sudo tee /etc/nginx/sites-available/nextjs > /dev/null <<'EOF'server { listen 80; server_name app.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_buffering off; }}EOF
You need a domain with an A record that points to your server IP. If you don't have one, you can register a domain and add the A record in the DNS panel. Check that the domain points to your server:
dig +short app.example.com
After creating the Nginx config file enable the site and remove the default one:
sudo ln -s /etc/nginx/sites-available/nextjs /etc/nginx/sites-enabled/nextjssudo rm -f /etc/nginx/sites-enabled/default
Test the config and reload Nginx:
sudo nginx -tsudo systemctl reload nginx
Also, test the site over HTTP with the following curl command:
curl -I http://app.example.com
In the output, you should see HTTP/1.1 200 OK.
Step 7: Add HTTPS with Certbot
At this point, you can easily add a free HTTPS certificate from Let's Encrypt with Certbot. Also, Certbot sets up the redirect from HTTP to HTTPS.
Open ports 80 and 443 if you use UFW and get the certificate:
sudo ufw allow 'Nginx Full'sudo ufw statussudo certbot --nginx -d app.example.com
Certbot asks for your email and for you to accept the terms. Choose the redirect option when it asks. Then, test auto-renewal:
sudo certbot renew --dry-run
Check that HTTPS works and HTTP redirects:
curl -I https://app.example.comcurl -I http://app.example.com
Step 8: Test Everything
In this step, you must test the full setup including the response headers, the variables, streaming, and cache persistence.
1) Request and response test:
curl -I https://app.example.com/
Look for HTTP/2 200 and an x-nextjs-cache header (HIT, STALE or MISS).
2) Runtime vs build-time variables. Check the current values:
curl -s https://app.example.com/env
Change only the runtime value and restart without a rebuild:
RUNTIME_MESSAGE=changed APP_VERSION=v1 docker compose up -dcurl -s https://app.example.com/env
The runtime text changes to changed. The build-time text stays build-one. NEXT_PUBLIC_ values are written into the JavaScript during next build, so you must rebuild to change them.
3) Streaming test:
curl -N https://app.example.com/stream
The first line shows right away. The slow part arrives about 3 seconds later. If everything appears at once, check that Nginx has proxy_buffering off.
4) Cache persistence test. Wait over 60 seconds, then request the page twice so it is rebuilt and saved:
sleep 65curl -s https://app.example.com/ | grep -o "Generated at: [^<]*"curl -s https://app.example.com/ | grep -o "Generated at: [^<]*"
Check the cache files on the volume:
docker compose exec web ls /cache/v1
Restart the container and request the page again:
docker compose restart webcurl -s https://app.example.com/ | grep -o "Generated at: [^<]*"
The time after the restart must match the time before it.
5) Control test (optional). Remove the volume and repeat the test:
docker compose down -vAPP_VERSION=v1 NEXT_PUBLIC_BUILD_LABEL=build-one RUNTIME_MESSAGE=hello docker compose up -dsleep 65curl -s https://app.example.com/ | grep -o "Generated at: [^<]*"
The time resets, because the cache volume is gone. This proves the volume keeps the cache.
Step 9: Versioned Rollback
You can deploy a second version and roll back to the first one. Each image has a version tag, so a rollback only starts the old image. It needs no rebuild. To deploy version 2, run:
APP_VERSION=v2 NEXT_PUBLIC_BUILD_LABEL=build-two docker compose up -d --build
Check that version 2 is live:
docker images nextjs-vpscurl -s https://app.example.com/env
The build-time text should show build-two. Request the home page once after 60 seconds to check the Version: line shows v2.
Roll back to version 1:
APP_VERSION=v1 docker compose up -d
Check the rollback; it must shows build-one again:
docker compose pscurl -s https://app.example.com/env
The cache is saved in separate folders for each version. You can check them with:
docker compose exec web ls /cache
A rollback never reads cache entries made by another version. Old cache folders do not delete themselves. You can remove a folder you no longer need with:
docker compose exec web rm -rf /cache/v2
To keep the version between logins, you can save the values in a .env file next to compose.yaml:
cat > .env <<'EOF'APP_VERSION=v1NEXT_PUBLIC_BUILD_LABEL=build-oneRUNTIME_MESSAGE=helloEOF
Note: change APP_VERSION in .env every time you deploy or roll back. Values you type in the command line override the .env file.
Single-Server Cache vs Multi-Instance Cache
This setup works for one server with one container. The cache files live on one disk, and one process reads and writes them.
If you run more than one container or server, this is not enough. By default, each instance keeps its own cache, and revalidateTag() on one instance does not clear the others. For many instances, you need:
- A cache handler that stores data in a shared place such as Redis or S3.
- Tag coordination, using
refreshTags() in the handler.
- The same
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY on every instance.
- A
deploymentId to protect against version mismatch during rolling updates.
Note: Do not mount one folder on several containers and call it shared. Start with the single-server setup, and move to a shared store only when you add more instances.
Conclusion
You can now deploy Next.js on a VPS in a safe way. The app runs as a non-root user and listens only on localhost. It sits behind Nginx with HTTPS, keeps its ISR cache after restarts, and rolls back with one command. This works well for one server. If you run many servers, you must add a shared cache first.
If you don't want to manage Docker and Nginx manually, you can use a self-hosted platform like Coolify. If you run into build, DNS or SSL errors, check the Coolify troubleshooting guide.