Next.js multi-stage Docker file

CJ Hewett
2 min readApr 23, 2022

The example Dockerfile on the next.js website didn’t work for me. So after some tweaking, and turning it into a multistage Dockerfile to slim it down, I thought I’d share it in case someone else ran into the same problem.

This is a multi-stage Dockerfile split into the following three stages:

  • The first stage installs some packages for the Alpine Node image andcreates a working directory for the app. The Node packages are then installed after copying the package.json and yarn.lock file.
  • The second stage copies the Node modules from the deps stage, then copies all files in the directory the Dockerfile is in. yarn build is called to build the source code.
  • The last stage installs some packages and creates a non-root user to run as, then copies necessary from the builder stage. A .env file is copied from the same directory as the Dockerfile. The yarn serve command calls the serve script in package.json which calls next start . This starts the application in production mode.
# Install dependencies only when needed
FROM…

--

--

CJ Hewett
CJ Hewett

Written by CJ Hewett

🛹 Skateboarder. 🏂 Snowboarder. 🏄 Websurfer. I write monthly* about Cloud/DevOps/IoT. AWS Certified DevOps Engineer and Terraform Associate

Responses (1)