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
andyarn.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. Theyarn serve
command calls theserve
script inpackage.json
which callsnext start
. This starts the application in production mode.
# Install dependencies only when needed
FROM…