Moving a production Next.js app off Vercel to Coolify on Hetzner
How I moved Simple Commenter's API, workers and finally the website from Vercel to my own servers with Coolify: sizing, build settings, releases without downtime, backups, and what broke.
TL;DR
- I moved in steps over seven weeks: API and browser workers first, then the data layer, then the website. Vercel stayed runnable as the way back at every step.
- Coolify runs the containers, the proxy and the certificates. It never builds Next.js on the production server. Images are built elsewhere and shipped finished.
- Simple Commenter's Vercel usage fell from $102 a cycle to about $25 a month before the final switch, on one €35.49 Hetzner server. The hard lessons were small defaults: keep-alive timeouts, build-time variables, cache headers.
Jump to
Simple Commenter is a website feedback tool built on Next.js: a widget that loads on customers' sites, a dashboard, an MCP server, browser jobs that take screenshots and render PDFs, and a dozen scheduled jobs. Until September 2026 it all ran on Vercel, with MongoDB on a small Hetzner server in Helsinki.
On 17 November 2026 the last part, the website itself, moved to my own server. This is how I did it, with the configuration that runs, trimmed for reading.
Why I left Vercel
Vercel is a very good product, and I'd still start a new project there. These are the reasons it stopped fitting this one.
Cost. For the cycle ending 24 September, Simple Commenter's own Vercel usage was $102.14, most of it Fluid compute. The team bill was $117.53 with the Pro seat. Behind it were 352 active CPU-hours. Averaged out, that is half a CPU core busy all month. A €35 server does that comfortably.
Limits. Per-route function metrics returned HTTP 402 without Observability Plus, and request paths were visible for 12 hours. Included CDN requests ran out around day 18 of every cycle. And several things I depended on only exist on Vercel: the bot check, the visitor's country and IP headers, and the custom-domain API. Each needed a replacement before I could leave.
Data residency. This wasn't really Vercel's fault, since my functions already ran in Stockholm. But owning the servers makes the answer short. The database, the backups and the app now sit with an EU provider in Helsinki, and each workspace has a home region whose data stays there.
Control. I wanted the backend next to the database, warm processes instead of cold functions, and Chromium jobs with hard memory limits.
What Coolify gives you
Coolify is an open-source platform you install on your own server. You get:
- a web UI for projects, deployments, environment variables, logs and restarts
- a Traefik proxy with automatic Let's Encrypt certificates
- apps from a Git repository, a Dockerfile, an image or a Docker Compose file
- other servers managed from the same dashboard over SSH
That last point mattered later. My US and Australian servers are remote servers of the EU Coolify instance: one dashboard, three regions.
I considered K3s, but a one-node cluster adds a control plane to maintain and still has no failover. What I don't use Coolify for matters as much: building.
Sizing the server on Hetzner
The half-core average was a starting hypothesis, not a guarantee. The cost-optimised CX plans I'd planned on weren't available, so I took a CPX32: 4 shared vCPUs, 8 GB RAM, 160 GB disk, €35.49 a month before VAT, in Helsinki next to the database.
| Plan (Germany/Finland) | vCPU | RAM | Per month |
|---|---|---|---|
| CPX22 | 2 | 4 GB | €19.49 |
| CPX32 | 4 | 8 GB | €35.49 |
| CPX42 | 8 | 16 GB | €69.49 |
Add €0.50 for an IPv4 address and 20% for daily server backups. Two things I didn't know: old servers keep old prices (my Mongo CPX22 is on a legacy €7.99, and resizing it would move it to today's price), and Hetzner has no Australian location. For the US and Australia I used UpCloud: 2 cores and 4 GB each, €14.40 a month.
Then I measured. The real memory peaks were 720 MiB for the API and 969 MiB for the worker, against limits of 2 GiB and 3 GiB. In mid-November, CPU peaked at 23% (10-minute averages) and free memory never fell below about 3 GB. The surprise was that the server had no swap and committed up to 121% of its memory. Before adding the website, I added a 4 GB swap file as a cushion. No resize needed.
Step by step
1. Create the server
Plain Ubuntu, IPv4 and IPv6, your SSH key, backups on. Install updates and reboot. Then the basics: key-only SSH, a host firewall for both IPv4 and IPv6 that allows only SSH, HTTP and HTTPS, and unattended security updates without automatic reboots. Docker can bypass the host firewall for published ports, so publish nothing you don't need.
2. Install Coolify
ssh root@your-server-ip
curl -fsSL https://cdn.coollabs.io/coolify/install.sh | sudo bashThe official installer sets up Docker if needed, Coolify, its own PostgreSQL and Redis, and Traefik. Those databases belong to Coolify, not your app. Then:
- Create the admin account and turn off public registration.
- Point
coolify.example.comat the server and set it as the instance domain, so the dashboard gets HTTPS. - Turn off auto-updates. Platform updates should be a decision, not something that happens mid-release.
- Back up Coolify itself: dump its PostgreSQL and keep its
.env, which holds the key that decrypts every stored secret. Restore the dump once to prove it works.
3. Get the app in: from Git, or as a finished image
The usual Coolify path is to connect your repository and let it build on push. For a small site, that is fine. For a production Next.js app on the same server as its traffic, don't build there. An earlier Coolify build on my small WordPress server froze the site. On the CPX32, a test build with a 4 GiB limit ran out of memory inside that limit.
So each release is built once, as a Linux AMD64 image from the exact committed source, and shipped finished:
# The idea, simplified. My release script adds checks, locks and rollback.
SHA=$(git rev-parse HEAD)
docker buildx build --platform linux/amd64 \
--build-arg SC_RELEASE=$SHA -t myapp:$SHA --load .
docker save myapp:$SHA | gzip | ssh root@your-server-ip 'gunzip | docker load'No registry, no npm install in production. Before anything starts, the server checks the image's architecture, its non-root user and the Git SHA it carries.
In Coolify the app is a Docker Compose resource pinned to that image:
services:
api:
image: sha256:your-image-id # pinned, never "latest"
pull_policy: never # already on the host
restart: unless-stopped
env_file: /etc/myapp/runtime.env
cpus: 2
mem_limit: 2g
read_only: true
tmpfs:
- /tmp:size=128m
- /app/.next/cache:size=256m
networks: [coolify]
labels:
- traefik.enable=true
- traefik.http.routers.api.rule=Host(`api.example.com`)
- traefik.http.routers.api.entrypoints=https
- traefik.http.routers.api.tls.certresolver=letsencrypt
- traefik.http.services.api.loadbalancer.server.port=3000
logging:
driver: json-file
options: { max-size: "10m", max-file: "3" }
networks:
coolify:
external: trueThe browser worker is a second service from the same image, on a private network with no published port and its own limits. A screenshot job can't starve the API.
4. Build settings for Next.js
Self-hosting means standalone output: Next.js writes a self-contained server.js with a trimmed node_modules. I keep it conditional, so the same repository still deploys on Vercel during the move:
// next.config.js
const nextConfig = {
...(process.env.VERCEL ? {} : { output: "standalone" }),
};The Dockerfile, reduced to what matters:
FROM node:22-bookworm-slim AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM deps AS builder
COPY . .
ENV NEXT_TELEMETRY_DISABLED=1 NODE_ENV=production
# Public client settings are inlined at build time, so they go in here.
RUN set -a && . ./deploy/public-build.env && set +a && npm run build
FROM node:22-bookworm-slim AS runner
WORKDIR /app
ENV NODE_ENV=production PORT=3000 HOSTNAME=0.0.0.0
# Outlive Traefik's 90 s idle timeout, or POSTs fail with 502.
ENV KEEP_ALIVE_TIMEOUT=95000
RUN useradd --uid 1001 --no-create-home nextjs
COPY --from=builder --chown=nextjs /app/.next/standalone ./
COPY --from=builder --chown=nextjs /app/.next/static ./.next/static
COPY --from=builder --chown=nextjs /app/public ./public
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]Standalone output doesn't include public/ or .next/static. Copy them yourself, or every image and script returns 404.
Two more I found when they broke. With read_only: true, pages that revalidate on a timer logged "Failed to update prerender cache" until .next/cache and .next/server/route-cache got small in-memory mounts. And a tab opened before a release asks for JavaScript chunks the new container doesn't have. Vercel keeps old files for you. I now keep each release's /_next/static files on a shared volume for 14 days.
5. Environment variables
There are two kinds, and mixing them up is the classic self-hosting mistake.
NEXT_PUBLIC_* values are compiled into the JavaScript at build time. Setting them in Coolify's runtime environment does nothing for the browser. My first image passed one public variable to the build. The code read 19, and Vercel set 11 of them, including the Stripe key and most OAuth client IDs. Pages from that image would have shown broken billing and integration buttons. They now live in a committed deploy/public-build.env (they're public anyway), and a test fails if the code reads a public name the build doesn't pass.
Secrets are runtime only: a root-owned file on the server, mode 600, referenced by the Compose file, never in Git or the image.
install -m 600 -o root -g root /dev/null /etc/myapp/runtime.envTo check for gaps I compared variable names, never values, between Vercel and the server: 89 against 58. Most of the difference was region settings that releases write per role, and several Vercel names were read by no code at all. Don't copy Vercel's own VERCEL variable, or your code will think it's on Vercel.
6. Domains and TLS
For API hostnames, Coolify's Traefik and Let's Encrypt handle certificates. Add the DNS record and the domain, done.
The website went behind Cloudflare's free plan, which also replaced three Vercel features: the CDN, customers' custom domains (Cloudflare for SaaS includes 100) and the bot check (Turnstile). The order mattered:
- Move DNS first, changing nothing else. Every record "DNS only", compared one by one with an export of the old zone. Email records first, because a missing one fails silently. DNSSEC has to come off at the old provider before the nameserver change.
- Run the new website container dark. It answered only for the real hostnames, which didn't point there yet. I tested it with
curl --resolveand a browser that mapped the domain to the server. - Flip the records to proxied at a quiet hour, with an origin certificate on the server and TLS on "Full (strict)".
Turn off Bot Fight Mode, Rocket Loader, minification, email obfuscation and the Browser Integrity Check: they break embedded scripts, plugins, MCP clients and webhooks. Then make the origin accept web traffic only from Cloudflare.
7. Preview deployments
I kept Vercel's Git integration for branch previews during the move. Coolify can build previews from pull requests, but that means building on a server, which is what I avoid. When Vercel goes, previews go too.
Databases: running Mongo yourself
MongoDB runs on its own small Hetzner server: 2 vCPU, 4 GB, a single-member replica set so transactions work. The US and Australian servers run the regional API and a local Mongo side by side with fixed limits: 1,280 MiB for the API, 1,536 MiB for Mongo, a 512 MiB WiredTiger cache.
The best argument for self-hosting came from another product. Truth or Dare AI ran on MongoDB Atlas's free tier, which caps data plus indexes at 512 MB and rejects writes above it. It reached that ceiling, and the database outage on 11 October meant about 11.5 hours with no play. The move to Hetzner took about fifteen minutes of actual work:
# Its own database and a login with rights on that database only
mongosh --eval 'db.getSiblingDB("appdb").createUser({
user: "app_user", pwd: passwordPrompt(),
roles: [{ role: "readWrite", db: "appdb" }] })'
# Copy. Never restore Atlas's admin users over your own.
mongodump --uri="$ATLAS_URI" --out=/tmp/atlas-dump
mongorestore --uri="$TARGET_URI" --drop --nsExclude='admin.*' /tmp/atlas-dumpThen a rehearsal, a local test, the new connection string, a final sync and a redeploy. Dump and restore took 9 seconds each. What I learned across both databases:
- Exclude
admin.*on restore. An Atlas dump carries Atlas's admin users and can overwrite your login. - Scope every restore with
--nsIncludeonce two products share an instance. A blanket--droprestore rolls back the neighbour too. - Cap the pool. Mongoose defaults to 100 connections per serverless instance. I set
maxPoolSize=10. - Raise the open-file limit. A restore failed with WiredTiger
errno 24under Docker's default of 1,024. Mongo now runs with 64,000, which only applies when the container is recreated. - Rotate the log.
mongod.loghad reached 5.4 GB. - Delete what you leave behind. The old Atlas cluster wasn't terminated on time and billed $51.74 for October.
I also removed Redis in late October. It held 4.3 MB, and nearly every Redis change had brought a bug. Counters and rate limits moved into each server's memory, and short-lived records into Mongo collections with automatic expiry.
Backups you have actually restored
Hetzner's daily server backups copy the disk. They aren't database backups. So a systemd timer runs every six hours:
[Timer]
OnCalendar=*-*-* 00,06,12,18:10:00 UTC
RandomizedDelaySec=120
Persistent=trueEach run takes mongodump --oplog of every instance, encrypts the stream before it touches disk, uploads it to a private object storage bucket, and restores it into an isolated container with no network, twice, checking the two match. It keeps everything for 48 hours, one a day for 30 days and one a week for eight weeks. A backup counts as stale after seven hours without a capture or eight days without a restore.
The restore check earned its place. The first restore container ran out of memory at 768 MiB and now gets 2 GiB. One run failed during an object storage incident at the provider. Both would have stayed hidden until the day I needed a backup.
Two honest limits. Backups and servers share a provider, so a provider-wide outage hits both, and a second provider is the next step. And "restore verified" proves the archive restores. It doesn't prove it matches production. My targets are under 6 hours of lost data and under 8 hours to restore critical service. They stay targets until a timed recovery exercise proves them.
Monitoring
Three layers, three questions:
- Is it up, seen from outside? Monitors on the US and Australian servers check every region and each other. Three failures open an incident, three successes close it, one email per incident.
- How is it doing? A Hosting page in the admin shows requests, grouped errors, jobs, and host CPU, memory and disk every 30 seconds, kept for 90 days.
- What just happened? Coolify's container logs, or
npm run logs -- apiover SSH.
A healthy process is not proof that a real comment gets saved. Only an end-to-end check says the product works.
Releases without downtime
A release is one command. It builds the image once and streams it to all three regions: EU from my machine, the US and Australia from EU, so it crosses my home connection once. It takes about 11 minutes.
Coolify updates the API containers, gated on health checks, keeping the previous image for rollback. The website container runs blue/green outside Coolify, so a swap never restarts the API. The release starts the other colour on the new image, waits for its health check, gives Traefik a few seconds, then stops the old one with a 60-second grace period. If the new one never gets healthy, it's removed and the old one keeps serving.
It took three releases to reach zero errors, with a test request loop running throughout:
| Swap | Result | Why |
|---|---|---|
| First | a single 502 | Next.js closed its listener on SIGTERM while Traefik still routed to it |
| Second | about five seconds of 503s | The two colours had different Traefik labels for one overlap |
| Third | no failures, including inside the swap window | Drain in place, labels identical |
The fix was a drain. On SIGTERM, the readiness endpoint returns 503 while the server keeps serving for six seconds. Traefik checks readiness every two seconds and stops routing first:
labels:
- traefik.http.services.web.loadbalancer.healthcheck.path=/ready
- traefik.http.services.web.loadbalancer.healthcheck.interval=2s
- traefik.http.services.web.loadbalancer.healthcheck.timeout=1sReadiness doesn't touch the database, on purpose: a database blip shouldn't pull the only web server. And database changes stay backwards compatible, because old and new versions run side by side.
What broke or surprised me
- Keep-alive 502s. Traefik keeps idle backend connections for 90 seconds; Node closes them after 5. Requests sent on a closing socket failed, and Traefik retries GETs but not POSTs, so I saw a small, steady stream of failed POSTs. The fix was one line:
KEEP_ALIVE_TIMEOUT=95000, so the proxy always closes first. request.urlis not your domain. Self-hosted Next.js buildsrequest.urlfrom its own listener,http://…:3000, not the Host header. My origin checks rejected real requests until two releases taught the routing code to use the visitor's protocol and host.- Cloudflare's browser cache default. The zone's 4-hour Browser Cache TTL added
max-age=14400to pages that only sents-maxage, so browsers would have kept pages for hours after a release. I set it to "Respect Existing Headers" at the switch. - Custom domains behind the customer's own Cloudflare. Some customer portals already ran through their own Cloudflare. When their hostnames went active in my zone, traffic reached my server before it had a route for them, and they returned 503 for about three and a half hours. Never activate a custom hostname before your origin serves it.
- Crons run twice if you let them. At the switch I disabled Vercel's crons and enabled 12 systemd timers in the same minute, with a test that keeps the timers equal to
vercel.json. - Coolify keeps its own copy of your Compose file. Changing the file in the repository changes nothing on the server until you update the resource.
Cost before and after
| Period | Simple Commenter's Vercel usage | All hosting, per month |
|---|---|---|
| Cycle to 24 Sep, before the move | $102.14 | about €135 |
| Cycle to 24 Oct, API and workers on Hetzner | $42.72 | about €165, with three regions |
| From 7 Nov, widget calls direct, log drain gone | about $25 a month | not invoiced yet |
| After 17 Nov, website off Vercel | expected $0 | not invoiced yet |
Yes, the total went up first: the new US and Australian regions cost more than the October savings. The servers now are the EU application server (€35.49), the EU Mongo server (€7.99), US and Australia (€14.40 each), object storage (€6.49) and a small WordPress server (€3.99). Cloudflare is free up to 100 custom domains, and Redis Cloud's €5 is gone. The $20 Vercel Pro seat stays, because other projects on the team still use it. My hours aren't in the table. The last two rows are estimates until the first invoices after the switch arrive.
A checklist
- Measure first. Get the bill by line and per project, plus the CPU-hours behind it. Optimise on Vercel before moving anything.
- Move in steps, each with a way back. Keep the old platform runnable until the new one has held for weeks.
- Size from averages, then measure peaks. Set container limits, add swap, leave room for two versions during a release.
- Never build on the production server. One image, from committed source, pinned by ID.
- Use standalone output, copy
public/and.next/static, and give caches writable mounts. - Pass every
NEXT_PUBLIC_*value to the build, with a test for missing ones. - Keep secrets in a root-only runtime file. Compare names between platforms, never values.
- Set
KEEP_ALIVE_TIMEOUTabove the proxy's idle timeout. - List the platform-only features (bot checks, geo and IP headers, custom domains, crons) and replace each before the switch.
- Move DNS without changing anything, record by record, email first.
- Encrypt backups, restore them automatically, and back up Coolify's database and
.envkey too. - Monitor from outside, from more than one place.
- Blue/green with a drain, tested with a request loop until a release shows zero errors.
- Turn the old things off. Crons, clusters and seats keep billing quietly.
When I wouldn't do this
If the Vercel bill is small and the team is busy, stay. Vercel handles deployment, previews, scaling, certificates and logs, and handles them well. Self-hosting means owning those jobs, plus the night the server goes down.
It made sense here because the workload was steady, the bill was mostly compute that one server handles easily, and I wanted the backend next to the database. The cost is that one server now holds the website: if Helsinki goes down, the site goes with it. Serving it from the US and Australian servers too is the next step, and it isn't done yet.