Blog>
Snippets

Using Docker to Create a Next.js 14 Container for Deployment

Illustrate the steps to build a Docker container for a Next.js 14 application, preparing it for deployment to any containerized environment.
const express = require('express');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});
This JS snippet creates a custom server using Express for a Next.js app, which is often not necessary for Next.js 14 unless specific server-side handling is desired. Replace 'const express = ...' and below with your Next.js app's server script if needed.
FROM node:16-alpine

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install
COPY . .

RUN npm run build

CMD ["npm", "start"]
This Dockerfile snippet sets up an Alpine-based Node.js environment, installs dependencies, copies your Next.js app into the Docker container, builds the application and defines the command to start the app.
version: '3'
services:
  nextjs-app:
    container_name: nextjs-container
    build: .
    ports:
      - '3000:3000'
    environment:
      - NODE_ENV=production
This docker-compose.yml snippet defines a service called 'nextjs-app' for a Next.js container, maps local port 3000 to Docker's port 3000, and sets the NODE_ENV to production.