Selecting a VPS Provider and Server Specifications
A production Next.js application handling typical SaaS traffic requires consistent CPU, memory, and fast storage. Target a VPS with at least 4 vCPU cores, 8 GB RAM, and 80 GB NVMe SSD. These specifications comfortably run the Next.js server, a PostgreSQL instance, Redis, and Coolify itself with headroom for traffic spikes.
Popular providers include Hetzner Cloud, DigitalOcean, and Linode. Hetzner offers excellent price-to-performance with European and North American locations. DigitalOcean provides simple billing and one-click Docker droplets. All three support IPv4, IPv6, and automated snapshots.
Choose a location closest to your primary users to reduce latency. For global audiences, consider a CDN in front of your self-hosted origin. Avoid burstable CPU instances for sustained workloads; dedicated vCPU plans deliver more predictable performance under load.
Operating system choice is Ubuntu 22.04 LTS or 24.04 LTS. These versions receive long-term Docker and security updates. After provisioning, immediately update packages with apt update && apt upgrade -y and configure unattended-upgrades for automatic security patches.
Server Preparation and Docker Installation
Before installing Coolify, harden the base server. Create a non-root user with sudo privileges, disable password authentication for SSH, and enforce key-based login only. Configure UFW firewall to allow ports 22, 80, 443, and 8000 (for Coolify dashboard during setup).
Install Docker using the official convenience script that pins verified packages:
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker $USER
Log out and back in to activate the docker group. Verify with docker run hello-world. Install Docker Compose v2 as a plugin:
sudo apt install docker-compose-plugin
Enable automatic Docker service startup and create a dedicated directory for Coolify persistent data: mkdir -p /opt/coolify. These steps ensure the host is ready for Coolify, which orchestrates additional containers through the Docker socket.
Installing Coolify v4
Coolify v4 provides a Vercel-like interface for self-hosted environments. The official installation command sets up the Coolify container, a PostgreSQL metadata database, and configures Caddy as the reverse proxy:
curl -fsSL https://cdn.coolify.io/q/install.sh | bash
After installation, access the dashboard at http://YOUR_SERVER_IP:8000. Complete the first-time setup by creating an admin account. Coolify automatically detects Docker and begins managing resources. The dashboard runs on port 8000 initially; you will later proxy it or restrict access.
Update Coolify regularly through its built-in updater. Version 4 introduces improved multi-server support, better resource monitoring, and native templates for common services. Keep the host kernel updated and monitor the Coolify logs via docker logs coolify during initial configuration.
Preparing a Next.js 15 Application for Self-Hosting
Next.js 15 works well in self-hosted environments when configured for standalone output. This mode produces a minimal artifact that includes only necessary dependencies and a server.js entrypoint.
Add the following to next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'standalone',
experimental: {
serverComponentsExternalPackages: ['@node-rs/argon2'],
},
};
export default nextConfig;
The standalone output creates a standalone folder after build containing server.js, static assets, and a node_modules pruned to production dependencies. This significantly reduces image size and startup time compared to the default build.
Create a minimal Dockerfile that works with Coolify's build system:
FROM node:20-alpine AS base
WORKDIR /app
FROM base AS deps
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
FROM base AS builder
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM base AS runner
ENV NODE_ENV=production
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
COPY --from=builder /app/standalone ./
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
ENV PORT=3000
CMD ["node", "server.js"]
This multi-stage build keeps final images under 180 MB. Coolify can use this Dockerfile automatically when it detects one in the repository root.
Deploying the Next.js Project in Coolify
In the Coolify dashboard, click "New Project" and select "Service" then "Docker". Connect your GitHub, GitLab, or Bitbucket account. Choose the repository containing your Next.js application.
Set the build command to npm run build and the start command to node server.js. Coolify detects the Dockerfile and uses it. If you prefer zero-config, set the base directory to ./, enable the standalone output flag, and Coolify will handle the build internally using its Nixpacks builder.
Resource limits are critical. Assign 2 CPU cores and 4 GB memory to the container for a medium-traffic application. Set health checks to GET / on port 3000 with a 10-second interval. Enable automatic restarts on failure.
After the first deployment, Coolify creates a preview URL. Subsequent pushes to the configured branch trigger new builds. Build cache is preserved between deployments, reducing build times from 45 seconds to under 15 seconds for typical code changes.
Integrating PostgreSQL and Redis Services
Most Next.js SaaS applications require a database. Coolify offers one-click templates for PostgreSQL 16 and Redis 7.
Deploy a new "Database" resource and select PostgreSQL. Choose version 16.3. Set a strong password and enable automatic backups. Coolify creates a dedicated Docker network so your Next.js service can reach the database using the internal hostname postgresql.
Connection string format becomes:
postgresql://postgres:[PASSWORD]@postgresql:5432/saas?sslmode=disable
For Redis, use the official Redis 7 template with persistence enabled. This instance serves as cache, session store, and rate-limiter backend. Configure connection using environment variables REDIS_URL=redis://redis:6379.
Both services receive automatic version updates through Coolify's template system. Monitor disk usage because PostgreSQL WAL files and Redis RDB snapshots can grow quickly under heavy write loads. Set volume size alerts at 75% capacity.
Secure Environment Variable Management
Coolify provides encrypted secret storage at project and organization levels. Never commit .env.production files. Instead, define variables in the Coolify UI under the "Variables" tab.
Mark sensitive values (database passwords, JWT secrets, OpenAI API keys) as "Secret". These are encrypted at rest using AES-256. For multi-environment setups, create separate "Production" and "Preview" variable sets that Coolify applies automatically based on branch.
Rotate credentials every 90 days. Use the built-in "Pull secrets from Doppler or Infisical" integration if your team already manages secrets centrally. For local development parity, maintain a .env.local file that is gitignored and document the exact variable names in your README.
Custom Domains, SSL, and Reverse Proxy Configuration
Coolify ships with Caddy v2 as the global reverse proxy. In the project settings, add your domain under "Domains". Coolify automatically provisions Let's Encrypt certificates and configures HTTP-to-HTTPS redirects.
For wildcard domains (*.example.com) used in multi-tenancy, provide a Cloudflare API token with DNS edit permissions. Caddy will solve the ACME challenge via DNS-01.
Configure security headers at the proxy level. Add these directives to the custom Caddyfile snippet in Coolify:
header {
Strict-Transport-Security "max-age=31536000;"
X-Content-Type-Options "nosniff"
X-Frame-Options "DENY"
Referrer-Policy "strict-origin-when-cross-origin"
}
Point your domain's A record to the VPS IP. Propagation usually completes within 5 minutes. Test with curl -I https://yourdomain.com to confirm 200 status and correct security headers.
Monitoring, Logging, and Alerting
Observability prevents outages. Coolify includes basic resource graphs, but for production add Prometheus, Grafana, and Uptime Kuma using Coolify templates.
Deploy Uptime Kuma to monitor your application endpoint every 30 seconds. Configure alerts via email, Slack, or Telegram. Set up a dedicated "Monitoring" project in Coolify to keep these tools isolated.
Export Next.js logs using the built-in Pino or Winston transport to stdout. Coolify aggregates container logs. For advanced querying, add Loki and Grafana. Create a dashboard showing:
- Request latency (p95 under 300 ms target)
- Error rates (keep under 0.5%)
- Memory and CPU utilization per service
- Database connection count and query duration
Configure Prometheus to scrape the Next.js instance by exposing a /metrics endpoint with the prom-client npm package. Set alerts for memory usage above 85% or latency spikes.
Automated Backup and Disaster Recovery Strategy
Configure daily PostgreSQL backups through Coolify's built-in scheduler. Backups are stored on the host volume and can be copied to S3-compatible storage using rclone cron jobs.
Example backup command scheduled via Coolify's cron service:
pg_dump -Fc -h postgresql -U postgres saas > /backups/$(date +%Y-%m-%d).dump
Retain 7 daily, 4 weekly, and 3 monthly backups. Test restoration quarterly by spinning up a temporary Coolify project and importing the latest dump. Document the exact restore procedure in your runbook.
For the application code, rely on Git history. Keep the last 5 successful Docker images in Coolify's registry settings to allow instant rollback by selecting a previous deployment tag.
Security Hardening for the Self-Hosted Stack
Run all services with least-privilege users (the Dockerfile above already uses a non-root nextjs user). Enable Docker Content Trust and sign images if your registry supports it.
Install and configure Fail2Ban to protect SSH and the Coolify dashboard port. Use CrowdSec as a bouncer for additional behavioral blocking. Keep the attack surface minimal by exposing only ports 80 and 443 to the internet; access the Coolify dashboard through an SSH tunnel or WireGuard VPN when needed.
Implement database row-level security even though the instance is internal. Regularly scan dependencies with npm audit and update vulnerable packages immediately. Use Argon2id for password hashing instead of weaker algorithms. Enable automatic security updates for the host OS and reboot during low-traffic windows.
Horizontal Scaling with Multiple Nodes
Coolify v4 supports multiple servers. Add additional nodes via the "Servers" tab by installing a lightweight agent on each. Distribute services across nodes: place the database and Redis on a dedicated high-memory node, run Next.js application instances across two or more web nodes.
Use an external load balancer such as HAProxy or another Caddy instance with sticky sessions if your application uses server-side sessions. For truly stateless applications, store sessions in Redis and enable round-robin balancing.
Scale the Next.js service by increasing replicas in the Coolify service settings. Each replica runs in its own container. Test with 100 concurrent users using k6 scripts to validate that shared Redis and database can handle the load before adding nodes.
Migrating from Vercel to Self-Hosted Coolify
Export environment variables from the Vercel dashboard. Recreate them in Coolify with identical names. Update any Vercel-specific edge functions to run on the Node.js runtime instead.
Switch image optimization from Vercel's built-in service to Sharp by installing sharp and configuring images.unoptimized = false in next.config. For static assets, continue using a CDN such as Cloudflare or Bunny.net pointed at your origin.
Update your CI pipeline to push to your self-hosted registry or let Coolify build directly from Git. Run both environments in parallel for two weeks, monitoring error rates and latency. Once confident, update DNS records with a low TTL and cut over.
Decision Framework: Self-Host or Use Managed Platforms
Self-hosting with Coolify makes sense when monthly Vercel or Railway costs exceed $150, when regulatory requirements demand data residency, or when you need deep customization of the runtime.
Trade-offs include increased operational burden: you become responsible for OS patches, backup verification, and capacity planning. However, you gain predictable fixed costs, the ability to run resource-intensive background jobs without function timeouts, and full control over data.
Calculate break-even by comparing your projected traffic against managed platform pricing tiers. For teams already comfortable with Docker and Linux administration, Coolify reduces the complexity gap significantly compared to raw VPS management. Start with a single server, measure actual resource consumption over 30 days, then decide whether to scale vertically or horizontally.
Continue iterating by adding service templates for Meilisearch or Qdrant when your product requires them. The same Coolify project can grow from a simple marketing site to a complex multi-service SaaS without changing your deployment mental model.
