Blog
By Published 12 min read

Deploy Next.js to a VPS with Docker: 2026 Step-by-Step Guide

Deploy Next.js to a VPS with Docker, Caddy and GitHub Actions. Dockerfile, HTTPS, firewall, backups and rollbacks, plus when Vercel is the cheaper choice.

Working through a similar problem? Tell us what you want to build.

Legacies is an independent digital product brand based in Bucharest, Romania, founded by Horia Stan and Alexandru Tălnaci, and we run our own Next.js sites in Docker containers on a VPS.

To deploy Next.js to a VPS with Docker, you build a small image using the standalone output, run it with Docker Compose, and put a reverse proxy such as Caddy in front for HTTPS. The whole setup takes one to two hours the first time. The part people underestimate is not the deploy. It is the firewall, the backups and the updates you now own.

Quick answer

  • The stack: a Linux VPS, Docker and Docker Compose, a Next.js image built with output: "standalone", and Caddy for automatic HTTPS.
  • The deploy flow: build the image in GitHub Actions, push it to a registry, then pull and restart on the server over SSH.
  • The big gotcha: ports published by Docker can bypass your firewall rules. Publish only the proxy ports, and keep the app container on an internal network.
  • When to skip all this: a solo founder with one small app is usually better off on a managed platform. We compare the costs in Vercel vs self-hosting Next.js.

Is a VPS the right place for your Next.js app?

Be honest about this before you open a terminal. A VPS gives you a fixed monthly bill, full control and no per-seat pricing. It also gives you every job a platform would otherwise do: patching the OS, renewing certificates, watching disk space and restoring backups.

A VPS makes sense when:

  • You have steady traffic and a predictable bill matters.
  • You run more than the frontend: a database, a worker, a queue or a cron job.
  • Several developers deploy, and per-seat pricing hurts.
  • Your data must stay in a specific region.

A managed platform is the better choice when you are a solo founder with one app and nobody who enjoys servers. Our cost breakdown puts the hidden maintenance time at roughly 2-4 hours a month for a well-set-up server. Count that before you count the small VPS price.

What you need before you start

ItemWhat to pickNotes
VPS2 vCPU and 2-4 GB RAMNext.js builds are memory hungry. Build in CI, not on the server.
OSUbuntu LTS or Debian stablePick a release with security support left.
DomainAn A record pointing to the server IPNeeded for Caddy to get a certificate.
RegistryGitHub Container Registry or Docker HubHolds the images CI builds.
CIGitHub ActionsSee our CI/CD comparison.

Entry-level VPS plans from providers like Hetzner cost a few euros a month at the time of writing. Prices changed several times in 2026, so check the provider page before you plan around a number.

Step 1: Turn on standalone output

Next.js can trace exactly which files your app needs and copy only those into a small folder. That is what makes the Docker image small. Add one line to your config:

// next.config.ts
const nextConfig = {
  output: "standalone",
};
export default nextConfig;

After next build, you get a .next/standalone folder with a server.js file you can run with plain Node. The public folder and .next/static are not copied automatically, so your Dockerfile must copy them. The Docker guide for Next.js and the Next.js output docs describe the same approach.

Step 2: Write a multi-stage Dockerfile

Three stages keep the final image small: install dependencies, build, run.

FROM node:22-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci

FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0
ENV PORT=3000
RUN addgroup -S app && adduser -S app -G app
COPY --from=builder /app/public ./public
COPY --from=builder --chown=app:app /app/.next/standalone ./
COPY --from=builder --chown=app:app /app/.next/static ./.next/static
USER app
EXPOSE 3000
CMD ["node", "server.js"]

Three details matter here:

  • Run as a non-root user. If the app is ever compromised, the attacker does not get root in the container.
  • Set HOSTNAME to 0.0.0.0. Otherwise the server may listen only inside the container and the proxy cannot reach it.
  • Use npm ci, not npm install. It installs exactly what your lockfile says. That also helps with supply chain safety.

Add a .dockerignore with node_modules, .next, .git and any .env files. A .env copied into an image is a leaked secret waiting to happen.

Step 3: Prepare the server

Log in as root once, then lock things down.

  1. Create a deploy userAdd a non-root user with sudo, copy your SSH public key to it, and test logging in before you continue.
  2. Disable password loginSet PasswordAuthentication to no and PermitRootLogin to no in the SSH config, then reload the SSH service. Keep your current session open until you confirm the new login works.
  3. Turn on the firewallAllow ports 22, 80 and 443 only. With ufw that is three allow rules and one enable command.
  4. Install Docker EngineUse the official Docker install instructions for your distribution, not an old package from the default repositories.
  5. Enable automatic security updatesOn Ubuntu and Debian, the unattended-upgrades package installs security patches for the OS without you logging in.

The Docker and firewall trap

Docker edits the firewall rules itself. If you publish a port with ports: "5432:5432", that port can be reachable from the internet even when ufw says it is closed. This is a well-documented behavior and it has exposed plenty of databases.

The fix is simple. Publish only ports 80 and 443 on the proxy. Keep the app and any database on an internal Docker network with no ports entry. If you must publish something for local use, bind it to 127.0.0.1.

Step 4: Docker Compose with Caddy

Caddy gets and renews HTTPS certificates on its own. That removes the most annoying part of the classic nginx plus Certbot setup.

services:
  app:
    image: ghcr.io/your-org/your-app:latest
    restart: unless-stopped
    env_file: .env
    networks: [internal]

  caddy:
    image: caddy:2
    restart: unless-stopped
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./Caddyfile:/etc/caddy/Caddyfile
      - caddy_data:/data
    networks: [internal]

networks:
  internal:

volumes:
  caddy_data:

And the Caddyfile:

example.com {
  reverse_proxy app:3000
}

Replace example.com with your domain. Run docker compose up -d, and Caddy requests a certificate on the first visit. Keep the .env file on the server only, with tight file permissions, and never commit it.

Step 5: Deploy from GitHub Actions

Do not build on the server. A small VPS can run out of memory during next build and take your live site down with it. Build the image in CI instead.

The flow is:

  1. On every push to main, Actions builds the image and pushes it to the registry, tagged with the commit SHA.
  2. Actions connects to the server over SSH using a dedicated deploy key stored as an encrypted secret.
  3. The server pulls the new tag and runs docker compose up -d.
  4. A quick request to a health URL confirms the new version responds.

Tag images with the commit SHA and not only latest. That gives you a one-line rollback: change the tag back and run compose again. Pin third-party actions to a commit, because they run with access to your secrets.

Run tests and type checks in the same workflow before the image is built, so a broken commit never reaches the server.

Step 6: What most guides skip

The deploy works. Now make it survivable.

JobWhat to doHow often
BackupsSnapshot the VPS and dump the database to storage off the serverDaily, test a restore monthly
MonitoringAn external uptime check that alerts you by email or chatAlways on
LogsLimit Docker log size so they do not fill the diskSet once
OS updatesReview pending updates and reboot for kernel patchesMonthly
Image updatesRebuild on a newer Node base imageMonthly
Framework patchesBump Next.js when security releases shipWithin days

That last row is the one teams forget. Self-hosting means a Next.js security release is your problem, not your host's. We wrote about this in Next.js security updates as a maintenance task.

Also watch disk space. Old images pile up. A weekly docker image prune job keeps the server from filling quietly.

Common mistakes

  • Building on the server. Memory spikes during the build. Use CI.
  • Secrets in the image. Anything copied in with COPY . . and no .dockerignore can end up in the image layers.
  • Wrong environment variables. Variables prefixed with NEXT_PUBLIC_ are baked in at build time. Changing them on the server later changes nothing.
  • Forgetting the image cache. Next.js image optimization uses disk and CPU. On a tiny server, set limits or use a loader.
  • One server, no backup. A VPS is a single machine. Treat it as something that can disappear.

If your app came out of an AI coding tool, run the production launch checklist before you point a domain at it.

Where DockLab fits

Once the app is live, the daily work is the server itself: SSH in, read logs, edit a config, restart a container, check a file. That is why we built DockLab, now in beta. It puts SSH, SFTP, a terminal, a browser and an AI coding agent in one workspace, so you see the server and the fix in one window. You can see what it does on our products page. The DockLab blog also has a guide on deploying a Docker Compose app to a VPS.

Do it yourself or hand it off?

Doing it yourself is fine when the app is low risk, one person owns the server, and a few hours of downtime would be annoying rather than costly. Follow the steps above, write the monthly chores in a calendar and you will be fine.

Hand it off when the app takes payments or holds customer data, when nobody on the team wants to be on call, or when the stack spans a frontend, a database and workers. We build custom web apps and automations and set up hosting that fits the budget. You get all the access and files. Web apps start at 3,499 lei (about EUR 700), with a fixed price after a short call. See our services and what we have built, or write to [email protected].

If you already have a live site, our free website audit checks speed, mobile, basic SEO and accessibility in seconds, with no signup.

Frequently Asked Questions

Can I deploy a Next.js app to a VPS with Docker?

Yes. Enable output standalone in your Next.js config, build a multi-stage Docker image, and run it on the VPS with Docker Compose. Put a reverse proxy such as Caddy or nginx in front to handle HTTPS. Build the image in CI rather than on the server, because a small VPS can run out of memory during the build.

How much RAM does a VPS need for Next.js?

For running a small or medium Next.js app, 1-2 GB of RAM is often enough, and 2-4 GB gives comfortable room for the app, the proxy and a small database. Building on the server needs more memory than running the app, which is the main reason to build the image in CI and only pull it on the server.

Should I use nginx or Caddy for Next.js?

Both work well as a reverse proxy. Caddy gets and renews HTTPS certificates automatically with a two-line config, which makes it simpler for small teams. nginx is more widely documented and gives finer control, but you usually add Certbot and manage renewals yourself. Pick the one your team already knows.

Is self-hosting Next.js cheaper than Vercel?

The server is cheaper, but the total often is not. A small VPS costs a few euros a month at the time of writing, while self-hosting adds maintenance time for updates, backups and monitoring. It tends to win with several developers, steady traffic or extra services like workers and databases. A solo founder with one app is often cheaper on a managed platform.

Why is my Docker port open even though my firewall blocks it?

Docker adds its own firewall rules when you publish a port, and those can bypass tools like ufw. Publish only ports 80 and 443 on your reverse proxy, keep other containers on an internal Docker network without a ports entry, and bind any local-only port to 127.0.0.1.

How do I roll back a bad Next.js deploy on a VPS?

Tag every image with the commit SHA when CI builds it. To roll back, change the image tag in your Compose file to the previous SHA and run docker compose up -d. The old image is still in the registry, so the rollback takes seconds. Keep database migrations backward compatible so the old version still works.

Do I need Kubernetes to run Next.js in production?

No. For a small team and one or a few apps, Docker Compose on one server is simpler and cheaper to run. Kubernetes adds value when you need many services, automatic scaling across machines or strict high availability. If you reach that point, a managed container platform is usually a gentler step than running your own cluster.

Next.jsDockerDeveloper ToolsHosting
Website maintenance and updatesProjects we have builtFree website auditAbout Legacies