Introduction
Docker is a helpful tool in software development, especially when integration of new features and frequent deployments are required. This tool makes it easy to containerize applications and their dependencies, ensuring they remain consistent across various environments. In this article, you'll learn how to dockerize a Next.js application.
Prerequisites
Before getting started, you will need to have the following tools installed on your system:
Step 1: Create a Next.js App
If you don't have a Next.js app yet, create one using the following commands:
npx create-next-app my-next-app
cd my-next-app
Run npm run dev
to see if the app is running properly.
Step 2: Setup a Dockerfile
Create a file called Dockerfile
in the root of your Next.js app. This file will contain the following instructions for building a Docker image for your application:
FROM node:21
WORKDIR usr/src/app
COPY . .
RUN npm install
CMD ["npm", "start"]
From the file above, the:
FROM node:21
command defines the image we want to build from, often called the base image. Here, we used the latest version of Node available as seen from the Docker HubWORKDIR usr/src/app
specifies the working directory asusr/src/app
, for executing any command you add in the Dockerfile.COPY . .
command copies all the files and folders from the current directory to the working directory.RUN npm install
installs all the necessary dependencies inside the container.CMD ["npm", "start"]
command defines how to start the application in the container.
Step 3: Create a .dockerignore File
Create a .dockerignore file at the root of your app and add the code below
node_modules
.next
This allows Docker to know what to ignore during the build process.
Step 4: Build the Docker Image
Open your terminal and run the following command to build the Docker image:
docker build -t my-next-app .
This command tells Docker to build an image using the instructions in the Dockerfile and give it the name my-next-app
.
Step 5: Run the Docker Container
After successfully building the Docker image, run the container:
docker run -p 3000:3000 my-next-app
This command maps port 3000 on your local machine to port 3000 in the Docker container. Open your browser and navigate to http://localhost:3000 to see your Next.js app running inside a Docker container.
Conclusion
In this article, you learned how to dockerize your Next.js application by following the steps outlined.
Dockerizing a Next.js app allows for easy deployment and ensures consistency across environments. This approach makes project development and deployment processes more efficient and scalable.