Dockerizing a Next.js Static HTML app

This guide expects that you have basic knowledge of how docker and Next.js works. The configuration is meant to work with Next.js static HTML exports (without server). See the Next.js documentation for more information.

Create the default.conf

server {
   listen 80;
   root /usr/share/nginx/html;
   location /_next/static {
     # Provides caching for static assets, to improve server performance
     add_header Cache-Control "max-age=31536000";
   }
   location / {
     try_files $uri.html  $uri $uri/ /index.html;
     add_header Cache-Control "no-cache";
   }
 }

Update your package.json

...
"scripts": {
  ...
  "export": "next build && next export"
},
...

For more information on next export, see the documentation.

Export your app

npm run export

Create a Dockerfile for your app

# Use the alpine nginx image as a base
FROM nginx:alpine
# Copy the local nginx configuration folder
COPY nginx /etc/nginx
# Set the working directory to the default nginx html directory
WORKDIR /usr/share/nginx/html
# Remove the existing web files
RUN rm -rf ./*
# Copy the files from the static next export
COPY ./out /usr/share/nginx/html

See the documentation for the nginx docker image for more information.

Build the docker image

docker build -t <your-image-name> .

Run your image

docker run --name <your-container-name> <your-image-name>

Alternatively, you may use docker-compose

version: '3'

services:
  <your-container-name>:
    image: <your-image-name>
    restart: always
    ports:
      - 80:80

To manage the service:

# Run the docker-compose service(s)
docker-compose up -d

# Stop the docker-compose service(s)
docker-compose down

One Reply to “Dockerizing a Next.js Static HTML app”

  1. This is a wonderful article. If I may propose a change for my use case: 404 handling. So I added the 404 page for Next.js and this is my nginx config file just slightly altered from what you had to support 404 pages.
    The main takeaway is I do NOT default to index.html. So that may be an issue for some folks.

    “`
    server {
    listen 80;
    root /usr/share/nginx/html;
    error_page 404 /404.html;
    location /_next/static {
    # Provides caching for static assets, to improve server performance
    add_header Cache-Control “max-age=31536000”;
    }
    location / {
    try_files $uri.html $uri $uri/ =404;
    add_header Cache-Control “no-cache”;
    }
    }

    “`

Leave a Reply to Lane Cancel reply

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.