Welcome! This guide will walk you through building and running a Next.js app inside a Docker container. Whether you're new to Docker or just want a quick reference, you'll find step-by-step instructions and explanations below.
You can find all the example files here.
Step 1: Define Services with Docker Compose
The docker-compose.yaml file helps you manage multi-container Docker applications. Here, we define a single service for our Next.js app.
1version: "3"2services:3 nextjs:4 build:5 context: .6 dockerfile: Dockerfile7 ports:8 - "5000:3000"9 environment:10 - NODE_ENV=productionStep 2: Create a Dockerfile
The Dockerfile contains instructions for building your app image. It sets up Node.js, clones your project, installs dependencies, and prepares the app for production.
1FROM node:20-bullseye2WORKDIR /app3RUN apt update && apt install git4RUN apt update && apt install -y git && rm -rf /var/lib/apt/lists/*5
6RUN rm -rf /app/* && if [ ! -d "/app/.git" ]; then git clone https://github.com/dedkola/nextjs-docs.git /app; else cd /app && git pull; fi7
8RUN npm install9RUN npm run build10EXPOSE 300011CMD ["npm", "start"]Step 3: Build the Docker Image
Use the following command to build your Docker image. The --no-cache flag ensures a fresh build every time.
1docker build -t nextjs:latest . --no-cacheStep 4: Run Your App in a Container
Start your container and map port 5000 on your machine to port 3000 in the container. This lets you access your app at localhost:5000.
1docker run -p 5000:3000 -d nextjsStep 5: Tag Your Image
Tagging helps you organize and version your images, especially before pushing to a registry like Docker Hub.
docker tag image_name:tag username/repo:repo_tag
1docker tag nextjs:latest your-username/nextjs:latestStep 6: Push to Docker Hub
Share your image with others by pushing it to Docker Hub.
1docker push your-username/nextjs:latestStep 7: Pull and Use the Image
Anyone can pull your image and run the container using the following reference:
1dedkola/nextjs:latestFeel free to experiment and modify these files for your own projects. Docker makes it easy to package and share your applications!