If you want to host your static nextjs application using docker and nginx, follow the following steps:
- Create
Dockerfilein root of your project and paste following contents
# Stage 1: Build the Next.js app
FROM node:lts AS build-deps
WORKDIR /usr/src/app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
COPY . .
RUN yarn build
# Stage 2: Serve the Next.js app with NGINX
FROM nginx:1.12
# Copy NGINX configuration
COPY nginx.conf /etc/nginx/conf.d/default.conf
# Copy built assets from the previous stage
COPY --from=build-deps /usr/src/app/out /usr/share/nginx/html
# Expose port 80
EXPOSE 80
# Start NGINX in the foreground
CMD ["nginx", "-g", "daemon off;"]- Update your
next.config.mjsfile
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
output: 'export', // Add This line
images: {
unoptimized: true,
},
};
export default nextConfig;- Create
nginx.conffile in root of your project and paste following contents:
server {
listen 80;
server_name localhost;
location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|html|xml|otf|ttf|eot|woff|woff2|svg)$ {
root /usr/share/nginx/html;
access_log off;
expires 30d;
add_header Cache-Control public;
tcp_nodelay off;
open_file_cache max=3000 inactive=120s;
open_file_cache_valid 45s;
open_file_cache_min_uses 2;
open_file_cache_errors off;
}
location /_next/ {
root /usr/share/nginx/html;
try_files $uri $uri/ /_next/static/index.html;
}
location / {
try_files $uri $uri/ /index.html;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://localhost:3000;
proxy_redirect off;
}
error_page 404 /index.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Nice setup this is pretty close to how we’ve handled static deployments in a few projects as well.
One thing I’ve run into with similar Docker + Nginx + static export setups is around routing consistency after build, especially when serving multiple environments behind a reverse proxy. Everything looks fine in the container, but small differences in caching headers or fallback rules in Nginx can sometimes break client-side routing or cause 404s on refresh.
In one of our hosting setups, the issue was mainly related to how the fallback to index.html was being handled under different location blocks, so simplifying the routing rules and keeping a clean SPA fallback helped stabilize it across environments.