Dockerizing a Next.js Application using a Standalone Build
Introduction
Docker has gained popularity in recent years for enabling applications to be placed inside containers. These containers can be deployed to any environment and will work the same way in all of them, providing a uniform behavior regardless of the platform where the application runs. These containers use images, which are a copy or compressed snapshot of the application. By placing them within a container, they are displayed exactly as they are. This is one of those technologies that some were desperate for, while others don't realize they need it until they hear about it.
For its part, Next.js is the most popular React framework. As any other JavaScript application that uses a bundler such as webpack or Vite, for production a compiled version of the project is used. This is known as build. A build aims to provide the minimum amount of code needed for the application to function the same as it does in development. This ensures that JavaScript files are very lightweight, allowing the browser to fetch and interpret them in the shortest possible time to render the user interface or perform whatever tasks the application requires."
Next.js, specifically, offers a version that further reduces the build size: the Standalone Build. If we use Docker to create an image for our Next.js application, we can easily deploy that great application that we have built to any environment without worrying about compatibility or additional configurations. In this article, we'll see how to achieve it.
Package manager
In my case, I like to use pnpm to reduce the disk size of the node_modules folder. Therefore, the example of the Next.js Docker image uses this package manager, but you can make slight adjustments to use npm or yarn if you prefer.
Next.js configuration
In the next.config.js file, we have to specify that the resulting build type will be standalone when the application is compiled for production. For this, we need to include the following:
/** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone" }; export default nextConfig;
This way, the output of the application will be of type standalone.
Dockerfile
The file that represents our Docker image is the Dockerfile. Commonly this file is placed in the root of the project. Let's create it step by step.
Base image
Every Docker image starts from a base image. In this case, any JavaScript project that runs a server, will need a runtime like Node.js. We'll take as base the Docker image of a Node.js version that is compatible with our project. In my case, I like to use the Alpine version of the images, since this is more lightweight. However, we have to check that there are no compatibility issues when building the image, otherwise, we have to use the "non-Alpine" version of the image. For this example, I use the node:22.6.0-alpine3.19 image as base.
/** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone" }; export default nextConfig;
We place an alias to recycle it in the different steps or stages of the image.
System and pnpm dependencies
The next stage is to install the dependencies. In this case, only one system dependency is required: libc6-compat. Here it is mentioned why.
FROM node:22.6.0-alpine3.19 AS base
Since pnpm isn't included by default in Node.js, it is necessary to activate it and set the environment variables so as the installed packages can be cached.
FROM base AS build-deps RUN apk add --no-cache libc6-compat
Then, we have to set the working directory to have a clear separation between the system folders and the application folder. In this case, we use /app.
ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable RUN corepack prepare pnpm@latest --activate
Now we have to copy the files containing the project dependencies information and install them.
WORKDIR /app
The --frozen-lockfile and --prefer-frozen-lockfile arguments are used to respect the versions specified in the lock file of pnpm.
To finish with this stage, the sharp library is added. This is necessary to optimize images in a production environment in Next.js.
COPY package.json pnpm-lock.yaml ./ RUN pnpm install --frozen-lockfile --prefer-frozen-lockfile
The full stage looks like this:
RUN pnpm add sharp
Building the application
The next stage is to compile the Next.js application. This is where the key for making the image work lies, because the rest of the Dockerfile isn't anything different or that you can't find in any other example. At this stage it is necessary to pass as build arguments the environment variables used in the project and set them before generating the build.
This is because, as there are two times in which the applications work, build time and run time, if the environment variables are not available at run time, all the static assets that use them won't have a value for them and the application won't work properly. In this example, three environment variables are used: NEXT_PUBLIC_BACKEND_URL, FRONTEND_URL and JWT_SECRET.
FROM base AS build-deps RUN apk add --no-cache libc6-compat ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable RUN corepack prepare pnpm@latest --activate WORKDIR /app COPY package.json pnpm-lock.yaml ./ RUN pnpm install --frozen-lockfile --prefer-frozen-lockfile RUN pnpm add sharp
Then, pnpm is activated, the work directory is set, all the application files are copied and the build is generated.
FROM base AS builder ARG NEXT_PUBLIC_BACKEND_URL ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL ARG FRONTEND_URL ENV FRONTEND_URL=$FRONTEND_URL ARG JWT_SECRET ENV JWT_SECRET=$JWT_SECRET
The full stage looks like this:
RUN corepack enable RUN corepack prepare pnpm@latest --activate WORKDIR /app COPY --from=build-deps /app/node_modules ./node_modules COPY . . RUN pnpm build
Running the application
The last stage is to run the application. To do this, we first set the Node production environment:
/** @type {import('next').NextConfig} */ const nextConfig = { output: "standalone" }; export default nextConfig;
For personal preference, Next.js telemetry is disabled. That is, we basically don't send our application data to Vercel to improve Next.js through error diagnosis and usage metrics.
FROM node:22.6.0-alpine3.19 AS base
Also, as a good practice, it is recommended to use a non-root user in Docker images. This, for instance, avoids security breaches in case the container has access to the host network. To do this, a nodejs group and a nextjs user are added and assigned the .next folder property.
FROM base AS build-deps RUN apk add --no-cache libc6-compat
Then, the files generated by the standalone build are copied to create the same structure of the default build of Next.js.
ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable RUN corepack prepare pnpm@latest --activate
Since we created the nextjs user, we need to specify that this will be the user to use.
WORKDIR /app
Likewise, it is required to specify the exposed port of the container, as well as the Node port and the hostname that will be used, which will be 0.0.0.0 since we don't know the exact address.
COPY package.json pnpm-lock.yaml ./ RUN pnpm install --frozen-lockfile --prefer-frozen-lockfile
Then, the environment variables for the application runtime are specified from the build arguments.
RUN pnpm add sharp
Specified environment variables in a docker-compose.yml file can be used, as well as when running the container, however, it wouldn't make sense for the environment variables in this context to be different at build time and run time.
Finally, we run the server.
FROM base AS build-deps RUN apk add --no-cache libc6-compat ENV PNPM_HOME="/pnpm" ENV PATH="$PNPM_HOME:$PATH" RUN corepack enable RUN corepack prepare pnpm@latest --activate WORKDIR /app COPY package.json pnpm-lock.yaml ./ RUN pnpm install --frozen-lockfile --prefer-frozen-lockfile RUN pnpm add sharp
Complete file
The complete Dockerfile looks like this:
FROM base AS builder ARG NEXT_PUBLIC_BACKEND_URL ENV NEXT_PUBLIC_BACKEND_URL=$NEXT_PUBLIC_BACKEND_URL ARG FRONTEND_URL ENV FRONTEND_URL=$FRONTEND_URL ARG JWT_SECRET ENV JWT_SECRET=$JWT_SECRET
You can also find the file in this gist.
Conclusion
Creating a Docker image for a Next.js application can be daunting at first because of all the considerations we have to take into account. In addition, there is the popular belief that self-hosting a Next.js application, i. e., outside Vercel, is complicated. It isn't. By understanding the key parts, it's actually simple.
I hope that with this information you can dockerize your Next.js application without problems. And you know the drill, if you have any question or want to share something, leave it in the comments :)
The above is the detailed content of Dockerizing a Next.js Application using a Standalone Build. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.
