How to Dockerize NextJS and Publish it to a Git Registry

Next JS Docker Github

Learn how to Dockerize your NextJS application and publish it to a Git registry. This comprehensive guide covers everything from creating a Dockerfile to automating the deployment process with CI/CD pipelines, ensuring efficient workflow and consistent application behavior across various environments.


NGNishan Giri
2024-06-07
How to Dockerize NextJS and Publish it to a Git Registry

In today's fast-paced development environment, containerization has become a critical skill for web developers. Docker allows us to package applications with all their dependencies, ensuring consistent behavior across different environments. When combined with NextJS, a powerful React framework, and Git, a robust version control system, you can streamline your development workflow and enhance collaboration.

In this comprehensive guide, we will walk you through the process of Dockerizing a NextJS application and publishing it to a Git registry. By the end of this tutorial, you'll have a solid understanding of Docker basics, how to containerize your NextJS app, and the steps to automate the process using CI/CD pipelines. Let's get started!

Table of Contents

Introduction

Containerization has revolutionized the way we develop, deploy, and manage applications. Docker, a popular containerization platform, enables developers to package applications along with their dependencies into a standardized unit called a Docker image. This image can then be run in any environment that supports Docker, ensuring consistent behavior across development, testing, and production environments.

NextJs, a React framework for production, enables developers to build server-side rendering and static web applications easily. By containerizing a NextJS application, we can ensure that it runs smoothly in different environments without any dependency issues.

In this tutorial, we will learn how to Dockerize a NextJS application and publish it to a Git registry. This process involves several steps, including writing a Dockerfile, building the Docker image, running the Docker container, and automating the process using Continuous Integration/Continuous Deployment (CI/CD) pipelines.

Prerequisites

Before we start, make sure you have the following software installed on your system:

Additionally, you should have a basic understanding of the following concepts:

Setting Up the NextJS Project

First, let's set up a basic NextJS project. If you don't have an existing NextJS project, you can create one using the following command:

npx create-next-app@latest my-nextjs-app
cd my-nextjs-app

This will create a new NextJS application in the my-nextjs-app directory. You can start the development server to ensure everything is set up correctly:

npm run dev

Open your browser and navigate to http://localhost:3000. You should see the default NextJS welcome page.

Writing the Dockerfile

A Dockerfile is a text document that contains instructions for Docker to build an image. Let's create a Dockerfile in the root directory of your NextJS project. Here’s an example Dockerfile for a NextJS application:

# Stage 1: Install dependencies only when needed
FROM node:16-alpine AS deps
WORKDIR /app
COPY package.json yarn.lock ./
RUN yarn install --frozen-lockfile
 
# Stage 2: Rebuild the source code only when needed
FROM node:16-alpine AS builder
WORKDIR /app
COPY . .
RUN yarn build
 
# Stage 3: Production image, copy all the files and run next
FROM node:16-alpine AS runner
WORKDIR /app
ENV NODE_ENV production
COPY --from=builder /app/public ./public
COPY --from=builder /app/.next ./.next
EXPOSE 3000
CMD ["node", "server.js"]

Explanation:

Using multi-stage builds helps keep the Docker image size small and optimized by separating the build and runtime environments.

Building the Docker Image

To build the Docker image, run the following command in the root directory of your project:

docker build -t my-nextjs-app .

This command will create a Docker image with the tag my-nextjs-app. You can verify the creation of the Docker image by running:

docker images

Running the Docker Container

Now that we have our Docker image, let's run it in a Docker container. Use the following command to run the Docker container:

docker run -p 3000:3000 my-nextjs-app

This will start the Docker container and map port 3000 of the container to port 3000 on your host machine. Open your browser and navigate to http://localhost:3000 to see your NextJS application running inside the Docker container.

Pushing the Docker Image to a Git Registry

To push your Docker image to a Git registry, you need to tag your image with the registry's URL. Here's an example using GitHub Container Registry:

  1. Login to GitHub Container Registry:
    echo $GITHUB_TOKEN | docker login ghcr.io -u USERNAME --password-stdin
  2. Tag the Docker image:
    docker tag my-nextjs-app ghcr.io/USERNAME/my-nextjs-app:latest
  3. Push the Docker image:
    docker push ghcr.io/USERNAME/my-nextjs-app:latest

Replace USERNAME with your GitHub username. This will push your Docker image to the GitHub Container Registry.

Automating the Process with CI/CD

To automate the process of building and pushing Docker images, we can use GitHub Actions. Create a .github/workflows/publish.yml file in your repository and add the following content:

name: Build and Push Docker Image
 
on:
  push:
    branches:
      - main
 
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Build the Docker image
        run: docker build . --tag ghcr.io/USERNAME/my-nextjs-app:latest
      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v1
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Push the Docker image
        run: docker push ghcr.io/USERNAME/my-nextjs-app:latest

This GitHub Actions workflow will automatically build and push your Docker image to the GitHub Container Registry whenever you push changes to the main branch.

Conclusion

In this tutorial, we covered the steps to Dockerize a NextJS application and publish it to a Git registry. By containerizing your NextJS application, you ensure consistent behavior across different environments, making your development workflow more efficient and reliable. Additionally, automating the process with CI/CD pipelines can significantly enhance your productivity.

We hope you found this guide helpful. Feel free to share your experiences or ask questions in the comments section below.

FAQs

  1. What is Docker and why should I use it? Docker is a platform that enables developers to package applications and their dependencies into a standardized unit called a Docker image. This image can run consistently across different environments, reducing the "it works on my machine" problem.

  2. Why use NextJS for my web applications? NextJS is a powerful React framework that enables server-side rendering and static site generation. It simplifies the development process and enhances the performance of web applications.

  3. How do I handle environment variables in Docker? You can use the ARG and ENV instructions in the Dockerfile to pass environment variables. For example:

    ARG NEXT_PUBLIC_API_URL
    ENV NEXT_PUBLIC_API_URL=${NEXT_PUBLIC_API_URL}

You can then pass these variables during the build process using the --build-arg flag.

  1. What is GitHub Actions? GitHub Actions is a CI/CD platform that allows you to automate your build, test, and deployment pipelines. You can create workflows that trigger on specific events, such as pushing changes to a branch.

  2. Can I use other Git registries besides GitHub Container Registry? Yes, you can use other Git registries such as GitLab Container Registry, Docker Hub, and others. The process is similar, but the commands and configuration may vary slightly.

By following these steps, you can improve your development workflow and ensure consistent application behavior across different environments. Automating the process with CI/CD pipelines can significantly enhance your productivity.

Happy Coding! 😊