Menu

Self-Hosting with Node.js and Docker

Lesson 3: Self-Hosting with Node.js and Docker

What are the self-hosting options?

Mode Config What you get Limits
Node.js server Default All features via next start You run and scale the server
Standalone output: 'standalone' A minimal server folder with only required node_modules Copy public and .next/static yourself
Static export output: 'export' Plain HTML, CSS, JS in an out folder No Server Actions, ISR, proxy, cookies(), or runtime caching

Example: Docker with standalone output

// next.config.ts
const nextConfig: NextConfig = { output: 'standalone' };
# Dockerfile
FROM node:22-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci

FROM node:22-alpine AS build
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .
RUN npm run build

FROM node:22-alpine AS run
WORKDIR /app
ENV NODE_ENV=production
COPY --from=build /app/.next/standalone ./
COPY --from=build /app/.next/static ./.next/static
COPY --from=build /app/public ./public
EXPOSE 3000
CMD ["node", "server.js"]
docker build -t learnhub .
docker run -p 3000:3000 --env-file .env.production learnhub

How it works

  • The multi-stage build keeps the final image small: only the standalone server, static files, and public.
  • Put a reverse proxy (such as Nginx or a cloud load balancer) in front for HTTPS and compression.
  • Multiple instances: the default cache is in memory per instance. When you run several containers, configure a shared cache handler (cacheHandlers in next.config.ts, e.g. backed by Redis) and set a fixed deploymentId so instances agree on cache keys.
  • next/image optimisation works on a Node.js server; for static export you need a custom loader or pre-optimised images.

Common mistakes

Mistake Effect Fix
Forgetting to copy .next/static and public Missing CSS, JS, and images Copy both into the image
Several instances with in-memory cache Users see different versions after revalidation Use a shared cache handler
Choosing static export for an app with login Auth and actions do not work Use a Node.js server
Running as root in the container Larger security risk Add a non-root user in the Dockerfile

Key takeaways

  • output: 'standalone' + Docker is a portable way to run Next.js anywhere.
  • Static export suits fully static sites only.
  • Share the cache when running more than one instance.

Try it: Build LearnHub into a Docker image with standalone output and run it locally on port 3000.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details