Mobile & DevOps

Deploy Next.js on GCP With PM2 and Nginx

A step-by-step VM setup for running Next.js on Google Cloud with PM2 and Nginx, plus when Cloud Run is the better choice.

By Devang GandhiUpdated Nov 3, 20268 min read

If you have searched for how to "deploy nextjs on gcp", you have probably seen five different answers: App Engine, Cloud Run, Firebase Hosting, GKE and plain VMs. They all work. The right one depends on what else runs next to your Next.js app.

My default for SaaS products with a Node API, Socket.IO and background jobs is a Compute Engine VM running PM2 behind Nginx. It is what I use on Antoc's infrastructure in asia-south1. This guide walks through the exact setup, the decisions behind it, and when I would pick something else.

TL;DR

Create a Compute Engine VM in the region nearest your users, reserve a static IP, install Node and Nginx, run next start and your API under PM2, and let Nginx handle TLS and proxying. Deploy by pulling, building and reloading PM2. Choose Cloud Run instead if the app is stateless and traffic is spiky.

key takeaways

  • A single Compute Engine VM with PM2 and Nginx is a cheap, predictable way to run Next.js plus a Node API and background workers.
  • Pick the region closest to your users, such as asia-south1 for India, because latency matters more than raw VM size.
  • Nginx should handle TLS, compression, request size limits and WebSocket upgrades so the Node processes only serve the app.
  • Cloud Run is better for spiky, stateless traffic, while a VM wins when you have Socket.IO, cron jobs and long-running workers.

VM or Cloud Run: picking the target

Before touching a terminal, be honest about the workload.

Factor Compute Engine VM + PM2 Cloud Run
Socket.IO / long connections Native, no limits beyond the box Possible, but request timeouts and instance churn complicate it
Cron jobs and workers Run as extra PM2 apps Needs Cloud Scheduler + separate jobs
Headless browsers (Playwright) Works with Xvfb if needed Heavier images, cold starts hurt
Cost at steady traffic Flat monthly price Can be higher if always warm
Spiky or near-zero traffic Paying for idle Scales to zero
Ops effort You patch the OS Google manages the runtime

For a CRM with realtime notifications, reminder crons and webhook consumers, the VM column wins almost every row. For a marketing site or a stateless API, Cloud Run is less work. Google's Compute Engine documentation covers machine types and regions in detail.

Step-by-step VM setup

This is the sequence I follow on a fresh Ubuntu LTS VM.

  1. Create the VM in your users' region (asia-south1 for India). Start with 2 vCPU and 4 to 8 GB RAM. Use a balanced persistent disk of at least 30 GB so builds and logs do not fill it.
  2. Reserve a static external IP and attach it. Ephemeral IPs change on stop/start and break DNS.
  3. Firewall rules: allow 80 and 443 from anywhere. Restrict SSH to your IP range or use IAP tunneling. Never expose the app port (3000) or the database port publicly.
  4. Create a deploy user without root, add your SSH key, and disable password login.
  5. Install Node through nvm or NodeSource, pinned to the same major version you use locally and in CI.
  6. Install PM2 globally and run pm2 startup systemd so processes come back after a reboot.
  7. Install Nginx and Certbot, point DNS at the static IP, and issue certificates with certbot --nginx.
  8. Clone, install, build: npm ci, then npm run build. Store secrets in an .env file readable only by the deploy user, or pull them from Secret Manager at boot.
  9. Start with an ecosystem file and save the process list with pm2 save.

A minimal ecosystem.config.js looks like this:

module.exports = {
  apps: [
    { name: 'web', script: 'node_modules/next/dist/bin/next', args: 'start -p 3000', instances: 2, exec_mode: 'cluster' },
    { name: 'api', script: 'server/index.js', env: { PORT: 4000 } },
    { name: 'cron', script: 'workers/cron.js', instances: 1 }
  ]
};

Keep cron workers at one instance. Two copies of a reminder job means every customer gets two reminders.

Nginx configuration that matters

Most Nginx tutorials stop at proxy_pass. These are the extra lines that prevent real production problems:

  • proxy_set_header Upgrade $http_upgrade; and Connection "upgrade" on the Socket.IO location, or realtime silently falls back to polling.
  • client_max_body_size set deliberately (for example 10m) so file uploads do not fail with a 413.
  • gzip on for text types, and long cache headers on /_next/static/, which is content-hashed and safe to cache for a year.
  • proxy_read_timeout raised for endpoints that legitimately run long, such as report exports.
  • Separate server blocks for the app domain and the API domain, so each can have its own limits and logs.

Test with nginx -t before every reload. A typo in a config file takes down every site on the box.

Logs, monitoring and deploys

A VM you cannot see into is a liability. My baseline:

  • PM2 logs rotated with pm2-logrotate so disks do not fill.
  • Sentry in both the Next.js app and the Node API for exceptions with stack traces.
  • Uptime checks from outside GCP hitting a lightweight /health route.
  • Disk and memory alerts through Cloud Monitoring.

For deploys, the simplest reliable flow is a GitHub Actions job that SSHes in (or runs on a self-hosted runner on the VM), pulls the branch, runs npm ci && npm run build, and calls pm2 reload ecosystem.config.js. reload restarts cluster instances one at a time, so users do not see an outage during the swap.

How I built this in practice

On Antoc, the real-estate CRM I work on at Passdn Technologies, the stack runs on GCP VMs in asia-south1 with PM2 and Nginx. The product serves 100+ real estate firms in India and around 300K leads, so most traffic comes from Indian users and Mumbai is the obvious region.

The VM approach fits because Antoc is more than a web app. There is a Next.js client, a Node/Express API, Socket.IO for realtime updates, scheduled WhatsApp nurture drips, and webhook receivers for Meta lead ads and Google Ads. A separate GCP VM runs the government tender intelligence bot, which drives Playwright inside Xvfb to scrape portals. None of that maps cleanly to scale-to-zero containers.

Sentry is wired into both client and server, and an automated SEO blog pipeline runs on a GitHub Actions self-hosted runner. The lesson from running it: keep each VM's job narrow and its PM2 process list readable, and you can reason about the whole system at a glance.

Common mistakes

  • Building on a tiny VM and running out of memory during next build, then blaming Next.js.
  • Leaving port 3000 open in the firewall so users bypass Nginx and TLS entirely.
  • Running cron workers in cluster mode, which duplicates every scheduled job.
  • Forgetting pm2 startup and pm2 save, so a routine reboot leaves the site down.
  • Putting the database in another region from the app and adding latency to every query.
  • Using pm2 restart instead of pm2 reload for cluster apps and causing brief outages on each deploy.

keep reading

FAQ

Is a VM or Cloud Run better for Next.js on GCP?+

Cloud Run is great for stateless apps with spiky traffic and no background work. A VM is simpler and cheaper when you also run Socket.IO, cron jobs, queues or headless browsers alongside the web app.

What machine size do I need for a Next.js app on Compute Engine?+

Many small production apps run comfortably on a 2 vCPU, 4 to 8 GB VM. The build step is usually the memory peak, so either size for the build or build in CI and ship the output.

Do I need Nginx if PM2 is already running Next.js?+

Yes, in practice. PM2 keeps the Node process alive, while Nginx terminates TLS, compresses responses, caches static assets and proxies WebSocket upgrades. They do different jobs.

How do I get HTTPS on a GCP VM?+

Point your domain's A record at a static external IP, open ports 80 and 443 in the VPC firewall, and use Certbot with the Nginx plugin to issue and auto-renew a Let's Encrypt certificate.

Which GCP region should I choose for an Indian user base?+

asia-south1 in Mumbai is the usual choice for India. Put the database in the same region so every API call does not cross a continent.

Devang Gandhi

AI & full stack developer at Passdn, building CRMs, SaaS, AI agents and Flutter apps for clients in the US, UK, Australia, UAE and India. More about me

Read next

More in Mobile & DevOps