Next.js is a React Framework which provide a robust solution to build production grade web applications. In the cloud-native era, there is a need to containerize the web app to deploy in kubernetes environments. There are 2 popular ways to build the container image for the app.
With Docker Build
With Cloud Native Buildpacks
In this session, we would perform simple steps to containerize the webapp with docker build. For building Next.js app image with buildpack, please have a look into another blog - How to containerize Next.js app with buildpacks.
Initial setup
We can build a Next.js based webapp with npx create-next-app@latest. We can extend the web app with more functionalities and API's. Then we can add the Dockerfile in the root folder for the app.
It's recommended to get the app resources for deployment separately for the webapp so that the app image size can be reduced to minimum, so we can use Next.js feature for generating standalone output.
Above config will create a folder at .next/standalone which can then be deployed on its own without installing node_modules.
Prepare Dockerfile
The crude way to build container with Dockerfile would be to copy source-code to container created with Next.js builder image and build compile the app and expose the app for app with an endpoint.
There are many problems with above approach :
Container image will be bulky, on average 1gb or above.
It would expose security issues, as secure data as well as configs which needed only for build would be always available in container layers and can be exploited.
It would have maintenance and upgrade issues, as the entire image layers would need to be replaced to upgrade and change code in the webapp.
To solve the issues, we can use multi-stage builds for creating app image.
As part of this stage, we use the package.json to perform npm install and prepare the Next.js app env.
Stage-2: Perform app build
Using the image from previous stage, we can build the app image.
Stage-3: Create app runner image
Finally we build the app image with image from previous stage. We can secure this image with linux user having permission for app resources and expose on certain port.
Final Dockerfile
With the above steps, we would get the final Dockerfile with 3 stages, and the final stage for the build would produce a slim version of app image. The usual app size is approximately 200mb.
Conclusion
We can use the dockerfile to perform docker build operation docker build -t myapp . to produce app image.
As a result of the above build process, we can have the app image generated and verified with docker images. We can verify the built image with docker run.
Hope this blog will help my friends to get the steps to build docker image for app in quick steps. 🙂