Prerequisites
To follow this tutorial, you will need the following:- Node.js, version 18.x or later at the time of writing.
- npm, as a package manager for installing and maintaining dependencies. This usually comes bundled with Node.js.
- A foundational knowledge of Next.js.
- Docker to build standalone containers to serve your production app.
This guide assumes that you have basic knowledge of the above-mentioned technologies and tools. If you are not
familiar with any of them, it is recommended to review their official documentation and tutorials to get up to speed
before proceeding with this guide.
Scaffolding the Next.js app
Next.js offers a CLI tool to quickly scaffold a new project. Run the following command:3000. Go to http://localhost:3000 to see your app. The
dev server supports hot reloading, so it reloads the application when you make changes.
Building and Dockerizing a Next.js App
When it is time to deploy your app for production, simply run:.next directory.
Create the Docker Image
Below is a Dockerfile optimized for Next.js, using multi-stage builds for smaller images and best practices for dependency management.Dockerfile
nextjs-app image for the platform linux/amd64 and tags it as latest.
If you are locally testing your application, you can skip the platform key to build the images.
Run the Docker Image
Letβs run the Docker container using the image created of the Next.js application with the command below.-it: enables interactivity with TTY.--rm: tells the Docker Daemon to clean up the container and remove the file system after the container exits.--name nextjs-app: Name of the containernextjs-app.-e PORT=3000: Sets the environment variable PORT in Docker to3000.-d: Runs the container in detached (background) mode. You can skip the flag to see the logs directly in your terminal window.-p 3000:3000: Maps port 3000 on your host to port 3000 in the container.nextjs-appat the end is the name of the image.
http://localhost:3000 to see the Next.js application running inside the Docker
container.
Hurray π. Now we have created and packaged a Next.js app for production use.
Example app
with-docker example, which is an official example published by the Next.js team.