Deploy a Next.js App with Coolify v4: Complete Self-Hosting Guide

AI Bot
By AI Bot ·

Loading the Text to Speech Audio Player...

Introduction

Vercel, Netlify, Railway — these cloud platforms simplify deployment, but at what cost? Unpredictable bills, vendor lock-in, and total dependence on third-party services. In 2026, more developers are choosing self-hosting to maintain full control over their infrastructure.

Coolify v4 is an open-source deployment platform (PaaS) that you install on your own server. It offers the same features as Vercel — automatic Git deployments, SSL certificates, preview environments — but on your infrastructure, with no per-project fees.

In this tutorial, you will learn how to:

  • Install and configure Coolify v4 on a VPS
  • Deploy a Next.js application with Docker
  • Set up automatic deployments via GitHub/GitLab
  • Configure SSL certificates with Let's Encrypt
  • Set up monitoring and alerts
  • Manage multiple environments (staging/production)

Prerequisites

Before starting, make sure you have:

  • A VPS with at least 2 GB RAM and 2 vCPUs (DigitalOcean, Hetzner, OVH, etc.)
  • Ubuntu 22.04 or 24.04 installed on the VPS
  • A domain name pointing to your server
  • A Next.js application ready to deploy
  • Basic knowledge of Docker and Linux command line
  • A GitHub or GitLab account with your source code

What You'll Build

By the end of this tutorial, you'll have a complete deployment infrastructure:

  • A Coolify server managing your applications
  • A Next.js application in production with SSL
  • An automatic CI/CD pipeline triggered on every push
  • A monitoring system with alerts
  • Preview environments for every pull request

Step 1: Prepare the Server

1.1 Connect to the VPS

Connect to your server via SSH:

ssh root@your-server-ip

1.2 Update the System

apt update && apt upgrade -y

1.3 Configure the Firewall

Coolify requires certain ports to be open. Configure UFW:

ufw allow 22/tcp    # SSH
ufw allow 80/tcp    # HTTP
ufw allow 443/tcp   # HTTPS
ufw allow 8000/tcp  # Coolify UI
ufw allow 6001/tcp  # Coolify Websocket
ufw allow 6002/tcp  # Coolify API
ufw enable

1.4 Configure DNS

Before installing Coolify, point your domain to the server. Create these DNS records:

TypeNameValue
Acoolify.yourdomain.comSERVER_IP
A*.yourdomain.comSERVER_IP

The wildcard record (*) allows Coolify to automatically create subdomains for each application.

Step 2: Install Coolify v4

2.1 Run the Installation Script

Coolify provides an automatic installation script:

curl -fsSL https://cdn.coollabs.io/coolify/install.sh | bash

This script automatically installs:

  • Docker and Docker Compose
  • Coolify and its dependencies
  • A Traefik reverse proxy
  • A PostgreSQL database for Coolify

Installation typically takes 2 to 5 minutes.

2.2 Access the Interface

Once installation is complete, open your browser and navigate to:

http://your-server-ip:8000

You'll see the first admin account creation screen.

2.3 Create the Admin Account

Fill in the form with:

  • Email: your email address
  • Password: a strong password (minimum 12 characters)

Coolify redirects you to the main dashboard.

2.4 Configure Coolify's Domain

Go to Settings and configure:

Instance FQDN: https://coolify.yourdomain.com

This allows you to access Coolify via your domain instead of the IP with port 8000.

Step 3: Prepare the Next.js Application

3.1 Project Structure

Here's the minimal structure of a Next.js project ready for Coolify:

my-nextjs-app/
├── src/
│   └── app/
│       ├── layout.tsx
│       └── page.tsx
├── public/
├── next.config.js
├── package.json
├── Dockerfile
└── .dockerignore

3.2 Create the Dockerfile

Create a Dockerfile at the root of your project:

FROM node:20-alpine AS base
 
# Install dependencies only when needed
FROM base AS deps
RUN apk add --no-cache libc6-compat
WORKDIR /app
 
COPY package.json package-lock.json* ./
RUN npm ci --only=production
 
# Builder
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
 
ENV NEXT_TELEMETRY_DISABLED=1
ENV NODE_ENV=production
 
RUN npm run build
 
# Production runner
FROM base AS runner
WORKDIR /app
 
ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
 
RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs
 
COPY --from=builder /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
 
USER nextjs
 
EXPOSE 3000
 
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
 
CMD ["node", "server.js"]

3.3 Configure Next.js for Standalone

Modify your next.config.js to enable standalone mode:

/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone',
}
 
module.exports = nextConfig

The standalone mode produces an optimized build that includes only the necessary files, significantly reducing the Docker image size.

3.4 Create the .dockerignore

node_modules
.next
.git
.gitignore
README.md
.env*.local

3.5 Test Locally

Verify that your Docker image works:

docker build -t my-nextjs-app .
docker run -p 3000:3000 my-nextjs-app

Open http://localhost:3000 to verify everything works.

Step 4: Connect the Git Repository

4.1 Add a Git Source

In Coolify, go to Sources then click Add:

For GitHub:

  1. Select GitHub App
  2. Click Register a GitHub App
  3. Give the app a name (e.g., coolify-my-server)
  4. Coolify redirects you to GitHub to authorize the application
  5. Select the repositories Coolify will have access to

For GitLab:

  1. Select GitLab
  2. Enter your GitLab instance URL
  3. Create an access token with api and read_repository scopes
  4. Paste the token in Coolify

4.2 Verify the Connection

Once configured, you should see your repositories listed when creating a new project.

Step 5: Deploy the Application

5.1 Create a Project

In Coolify:

  1. Click Projects in the sidebar
  2. Click Add
  3. Name your project (e.g., my-website)
  4. Select the Production environment

5.2 Add a Resource

  1. In your project, click New Resource
  2. Select Public Repository or Private Repository (GitHub/GitLab)
  3. Choose your repository
  4. Select the branch (main or master)

5.3 Configure the Deployment

Coolify automatically detects the project type. For Next.js with Docker:

Build Pack: Dockerfile

Network Configuration:

Exposed Port: 3000
Domain: https://myapp.yourdomain.com

5.4 Environment Variables

Add your environment variables in the Environment Variables tab:

DATABASE_URL=postgresql://user:password@db:5432/mydb
NEXT_PUBLIC_API_URL=https://api.yourdomain.com
SECRET_KEY=your-secret-key

Coolify automatically encrypts sensitive variables. You can also mark certain variables as Build time only or Preview only.

5.5 Launch the Deployment

Click Deploy. Coolify will:

  1. Clone your repository
  2. Build the Docker image
  3. Start the container
  4. Configure the Traefik reverse proxy
  5. Generate the SSL certificate via Let's Encrypt

Follow the progress in real-time logs.

Step 6: Configure Automatic SSL

6.1 Let's Encrypt Certificates

Coolify automatically manages SSL certificates via Let's Encrypt. Make sure that:

  • Your domain correctly points to the server
  • Port 80 is open (required for the HTTP-01 challenge)
  • The FQDN is correctly configured in the application settings

6.2 Verify the Certificate

After deployment, visit your site over HTTPS:

https://myapp.yourdomain.com

The padlock should appear in the address bar. The certificate renews automatically before expiration.

6.3 Force HTTPS

In the application settings, enable Force HTTPS to automatically redirect all HTTP traffic to HTTPS.

Step 7: Automatic Deployment (CI/CD)

7.1 Automatic Webhooks

If you connected Coolify via a GitHub App, webhooks are configured automatically. Every push to the configured branch triggers a new deployment.

7.2 Branch Configuration

You can configure different behaviors per branch:

main → Production (myapp.yourdomain.com)
develop → Staging (staging.myapp.yourdomain.com)

7.3 Preview Deployments

Coolify supports preview deployments for pull requests:

  1. In the application settings, enable Preview Deployments
  2. Each PR gets a unique subdomain: pr-42.myapp.yourdomain.com
  3. The preview is automatically removed when the PR is closed

This lets your team test every change before merging.

7.4 Rollback Strategy

If something goes wrong, Coolify keeps previous versions. To roll back:

  1. Go to the Deployments tab
  2. Find the previous deployment that worked
  3. Click Redeploy

Step 8: Add a Database

8.1 Create a PostgreSQL Database

Coolify can manage your databases with one click:

  1. In your project, click New Resource
  2. Select Database
  3. Choose PostgreSQL
  4. Configure:
Version: 16
Database Name: myapp_db
Username: myapp_user
Password: (auto-generated)
Public Port: (disabled by default - recommended)
  1. Click Start

8.2 Connect the Application to the Database

Coolify creates an internal Docker network. Use the container name as the host:

DATABASE_URL=postgresql://myapp_user:password@pg-container-name:5432/myapp_db

Add this variable in your Next.js application's Environment Variables.

8.3 Automatic Backups

Configure backups in your database's Backups tab:

  • Frequency: daily (recommended)
  • Retention: minimum 7 days
  • Destination: S3, local, or remote server
# Coolify can also send backups to S3
# Configure in Settings > S3 Storage

Step 9: Monitoring and Alerts

9.1 Built-in Metrics

Coolify displays basic metrics directly in the dashboard:

  • CPU: usage percentage
  • RAM: used / total memory
  • Network: incoming / outgoing traffic
  • Disk: used space

9.2 Health Checks

Configure a health check for your application:

Health Check Path: /api/health
Health Check Interval: 30 (seconds)
Health Check Timeout: 5 (seconds)
Health Check Retries: 3

Create the corresponding endpoint in your Next.js application:

// app/api/health/route.ts
import { NextResponse } from 'next/server'
 
export async function GET() {
  try {
    // Check database connection
    // await db.query('SELECT 1')
 
    return NextResponse.json({
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: process.uptime(),
    })
  } catch (error) {
    return NextResponse.json(
      { status: 'unhealthy', error: 'Database connection failed' },
      { status: 503 }
    )
  }
}

9.3 Notifications

Configure alerts in Settings > Notifications:

  • Email: email alerts (SMTP required)
  • Discord: webhook to a Discord channel
  • Telegram: notifications via Telegram bot
  • Slack: Slack integration

Example Telegram configuration:

  1. Create a bot via @BotFather on Telegram
  2. Get the bot token
  3. Get your chat ID
  4. Add this information in Coolify

You'll receive notifications for:

  • Successful or failed deployments
  • Failed health checks
  • SSL certificates about to expire
  • High resource usage

Step 10: Advanced Optimizations

10.1 Multi-stage Docker Cache

Optimize your builds by leveraging Docker cache. Coolify preserves Docker layers between builds, speeding up subsequent deployments.

Tip: place instructions that change rarely (like npm ci) before those that change often (like COPY . .) in your Dockerfile.

10.2 Resources and Limits

Configure resource limits for each container:

CPU Limit: 2 (cores)
Memory Limit: 1024 (MB)
Memory Reservation: 512 (MB)

This prevents a failing container from consuming all server resources.

10.3 Horizontal Scaling

For applications that need more capacity, Coolify supports:

Multiple instances:

Number of replicas: 3

Traefik automatically distributes traffic between instances (load balancing).

Remote servers:

  1. Go to Servers and add a new server
  2. Coolify connects via SSH
  3. You can deploy applications across multiple servers

10.4 Data Persistence

For uploaded files or persistent data, configure Docker volumes:

Source: /data/uploads
Destination: /app/public/uploads

This data survives redeployments.

Step 11: Security

11.1 SSH Key Access

Disable SSH password authentication:

# /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
systemctl restart sshd

11.2 Automatic Updates

Configure automatic security updates:

apt install unattended-upgrades -y
dpkg-reconfigure -plow unattended-upgrades

11.3 Update Coolify

Coolify updates from the interface:

  1. Go to Settings
  2. Check the current version
  3. Click Update if a new version is available

You can also enable automatic updates for Coolify.

11.4 Fail2ban

Protect your server against brute-force attacks:

apt install fail2ban -y
systemctl enable fail2ban
systemctl start fail2ban

Troubleshooting

Deployment Fails at Build

Problem: "Out of memory" error during npm run build

Solution: Increase available memory or add swap:

fallocate -l 4G /swapfile
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
echo '/swapfile none swap sw 0 0' >> /etc/fstab

Site Shows a 502 Error

Possible causes:

  • The container hasn't finished starting — wait a few seconds
  • The port configured in Coolify doesn't match the port exposed by the application
  • The application crashed — check the logs in Coolify

SSL Certificate Won't Generate

Check:

  • DNS correctly points to the server (dig myapp.yourdomain.com)
  • Port 80 is open
  • No Let's Encrypt rate limiting (5 certificates per domain per week)

Environment Variables Are Not Accessible

  • NEXT_PUBLIC_* variables must be available at build time
  • Mark them as Build Variable in Coolify
  • Redeploy after adding new variables

Coolify vs. Alternatives

FeatureCoolifyVercelNetlifyRailway
CostFree (self-hosted)From $20/monthFrom $19/monthPay-per-use
Open sourceYesNoNoNo
Automatic SSLYesYesYesYes
Preview deploysYesYesYesYes
DatabasesYes (built-in)NoNoYes
Full controlYesNoNoNo
Vendor lock-inNoneHighHighModerate

Next Steps

Now that your infrastructure is in place, here are some possible improvements:

  • Add a CDN: Configure Cloudflare in front of your server for caching and DDoS protection
  • Centralize logs: Integrate a logging stack like Grafana + Loki
  • Automate backups: Configure S3 backups with retention and encryption
  • Multi-server: Add servers in different regions for redundancy
  • Advanced monitoring: Deploy Uptime Kuma via Coolify to monitor your services

Conclusion

You now have a complete, self-hosted, and free deployment platform. Coolify v4 offers an experience comparable to Vercel or Netlify, but with full control over your data and infrastructure.

The main advantages of this approach:

  • Predictable cost: a fixed-price VPS instead of variable bills
  • Data sovereignty: your data stays on your server
  • Flexibility: deploy any type of application (not just supported frameworks)
  • No vendor lock-in: migrate to another server whenever you want

Self-hosting requires more responsibility in terms of maintenance and security, but tools like Coolify significantly reduce that burden. For teams and projects that value independence and control, it's a solid alternative to proprietary cloud platforms.


Want to read more tutorials? Check out our latest tutorial on Build Production AI Agents with the Claude Agent SDK and TypeScript.

Discuss Your Project with Us

We're here to help with your web development needs. Schedule a call to discuss your project and how we can assist you.

Let's find the best solutions for your needs.

Related Articles