DEV Community

Cover image for How to Easily Dockerize a Next.js Application
Emanuel Navarro
Emanuel Navarro

Posted on

How to Easily Dockerize a Next.js Application

Hi there! In this little post I'm going to show you how to use Docker to containerize your Next.js application.

What is Docker?

Docker is an open-source platform that enables developers to automate the deployment, scaling, and management of applications inside lightweight, portable containers. Containers are a way to package applications with their dependencies and runtime environment, allowing them to run consistently across different environments, such as development, testing, and production, without any compatibility issues.

Setting up a Next.js project

1.First we need to create a nextjs application.

npx create-next-app@latest project_name
Enter fullscreen mode Exit fullscreen mode

2.Create Dockerfile in the root directory of your project

//Dockerfile

FROM node:18-alpine

# Initialize a working directory in your new os
WORKDIR /app

# Copy package.json into the new working directory
COPY package*.json ./

RUN npm install

# Copy all the files from your current directory to the working directory of the container
COPY . .

# Expose port 3000 from your container to local network
EXPOSE 3000

CMD npm run dev

Enter fullscreen mode Exit fullscreen mode

3.Create the docker container

docker build -t next-docker-demo . 
Enter fullscreen mode Exit fullscreen mode

Where next-docker-demo is the image name.

. to tell docker that the Dockerfile is in current folder.

4.We can use docker compose, so we don’t need to remember long commands to build or run containers. We can simply just use docker-compose build and docker-compose up.

Add a docker-compose.yml file to your root directory.

version: '3.8'
services:
  app:
    image: next-docker-demo
    build: .
    volumes:
        - .:/app
        - /app/node_modules
        - /app/.next
    ports:
      - "3000:3000"
Enter fullscreen mode Exit fullscreen mode
docker-compose build
Enter fullscreen mode Exit fullscreen mode
docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

-d to run the the container in the background.

Now if you access http://localhost:3000, you will see your working app!

Top comments (0)