I am creating a Next.js project using Docker, but every time I run docker build
, the docker image is 300 MB+. My goal is to reduce the size of the docker image. For this I started using zeit/pkg but it doesn't work properly.
Question:
What files are required in Next.js for docker build
? (I see COPY . . in each tutorial)
And how can I reduce the size of the docker image?
I followed this tutorial: https://medium.com/@evenchange4/deploy-a-commercial-next-js-application-with-pkg-and-docker-5c73d4af2ee
Dockerfile:
FROM node:lts-alpine as build-env
WORKDIR /app
COPY . .
RUN yarn install --pure-lockfile --ignore-engines
ENV NODE_ENV=production
RUN yarn run build
RUN yarn run pkg
FROM node:alpine
RUN apk update && \
apk add --no-cache libstdc++ libgcc ca-certificates && \
rm -rf /var/cache/apk/*
WORKDIR /app
COPY --from=build-env /app/pkg .
ENV NODE_ENV=production
EXPOSE 8080
CMD ./next-app
package.json:
{
"name": "next-app",
"bin": "server.js",
"pkg": {
"assets": [
".next/**/*"
],
"scripts": [
".next/**/*.js"
]
},
"scripts": {
"test": "jest",
"dev": "next",
"build": "next build",
"start": "NODE_ENV=production node server.js",
"pkg": "pkg . -t node13-linux-x64 -o pkg"
},
"dependencies": {
"next": "^9.4.0",
"react": "^16.13.1",
"react-dom": "^16.13.1"
},
"devDependencies": {
"pkg": "4.4.8",
"typescript": "^3.9.2"
}
}
I know it has been over 5 months since this question was asked, but I was running in the same issue.
I solved it by setting up a multistage build in docker and only copy the required files to run a production nextjs app.
My Dockerfile
An excerpt from my package.json