This guide walks you through the entire process of deploying a Next.js application to a VPS using Docker and Docker Compose.
How to Deploy a Next.js App with Docker on a VPS
A complete step-by-step guide to deploying your Next.js application using Docker on a Virtual Private Server. From Dockerfile to live site.
Overview
Prepare Your Next.js Project
Before deploying, make sure your Next.js project is production-ready. Update your next.config.ts to enable standalone output:
const nextConfig = {
output: 'standalone',
};
export default nextConfig;Then test your production build locally:
npm run build
npm run startAlways test your build locally before deploying. This catches most issues early.
Create a Dockerfile
Create a multi-stage Dockerfile in your project root. This keeps the final image small and secure:
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
FROM node:20-alpine AS runner
WORKDIR /app
COPY --from=builder /app/.next/standalone ./
COPY --from=builder /app/.next/static ./.next/static
COPY --from=builder /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]Multi-stage builds reduce your final image size by up to 80%.
Make sure your .dockerignore includes node_modules and .next to speed up builds.
Set Up Docker Compose
Create a docker-compose.yml to orchestrate your services:
services:
app:
build: .
ports:
- '3000:3000'
environment:
- NODE_ENV=production
restart: always
nginx:
image: nginx:alpine
ports:
- '80:80'
- '443:443'
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf
depends_on:
- app
restart: alwaysSSH Into Your VPS and Clone
Connect to your VPS and set up your project:
ssh deploy@your-server-ip
# Install Docker if not already installed
curl -fsSL https://get.docker.com | sh
sudo usermod -aG docker $USER
# Clone your project
git clone https://github.com/your-repo.git
cd your-repoUse SSH keys instead of passwords for better security.
Never run containers as root in production.
Configure Environment Variables
Create your production .env file on the server:
cp .env.example .env
nano .envSet all required variables including database URLs, API keys, and secrets. Generate a secure secret:
openssl rand -base64 32Use a password manager to store your production credentials securely.
Never commit your .env file to version control. Add it to .gitignore.
Build and Deploy
Build and start your containers:
# Build and start in detached mode
docker compose up -d --build
# Check if everything is running
docker compose ps
# View logs
docker compose logs -f appYour app should now be live at your server's IP address or domain!
Set up a webhook or CI/CD pipeline for automatic deployments on git push.
You're Done!
Congratulations on completing this guide. You've successfully learned how to deploy a next.js app with docker on a vps.
Comments (0)
Leave a Comment