How to Deploy Next.js Using Docker: Step-by-Step Guide
To deploy a
Next.js app using Docker, create a Dockerfile that installs dependencies, builds the app, and starts the server. Then build the Docker image with docker build and run it with docker run. This packages your app and its environment for easy deployment.Syntax
A typical Dockerfile for Next.js includes these steps:
- Base image: Use an official Node.js image.
- Working directory: Set where app files live inside the container.
- Copy files: Copy
package.jsonand source code. - Install dependencies: Run
npm installoryarn. - Build app: Run
npm run buildto create production files. - Expose port: Open port 3000 for Next.js server.
- Start server: Run
npm startto launch the app.
dockerfile
FROM node:18-alpine WORKDIR /app COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["npm", "start"]
Example
This example shows a complete Dockerfile for a Next.js app and how to build and run it with Docker commands.
dockerfile
FROM node:18-alpine WORKDIR /app COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["npm", "start"]
Output
Docker image built successfully.
Container running and serving Next.js app on http://localhost:3000
Common Pitfalls
Common mistakes when deploying Next.js with Docker include:
- Not copying
package-lock.jsonoryarn.lock, causing inconsistent installs. - Forgetting to run
npm run buildbefore starting the server. - Exposing the wrong port or not exposing any port.
- Using a heavy base image instead of a slim one like
node:18-alpine. - Not setting the working directory, causing file path errors.
dockerfile
WRONG: FROM node:18 COPY . . RUN npm install CMD ["npm", "start"] RIGHT: FROM node:18-alpine WORKDIR /app COPY package.json package-lock.json ./ RUN npm install COPY . . RUN npm run build EXPOSE 3000 CMD ["npm", "start"]
Quick Reference
Summary tips for deploying Next.js with Docker:
- Use
node:18-alpinefor a small image. - Always run
npm run buildbefore starting. - Expose port 3000 to access the app.
- Set
WORKDIRto keep files organized. - Copy lock files to ensure consistent installs.
Key Takeaways
Create a Dockerfile that installs dependencies, builds, and starts your Next.js app.
Use a lightweight Node.js base image like node:18-alpine for smaller containers.
Always run npm run build before starting the server inside the container.
Expose port 3000 to allow access to the Next.js app from outside the container.
Copy package-lock.json or yarn.lock to ensure consistent dependency installation.