DEV Community

Cover image for Next.js app deployed with Docker - does it make sense?
Francesco Ciulla
Francesco Ciulla

Posted on

Next.js app deployed with Docker - does it make sense?

Hi, I am Francesco Ciulla, and I used Docker for ~10 years and Next.js for 5+ years.

In this article, I want to show you how you can dockerize a Next.js application, and after that, I will give some considerations.

If you prefer a video version:

All the code is available for free on GitHub (link in video description).

Create a Next.js app

To create a Next app, open your terminal, navigate any folder you want, and type:



npx create-next-app@latest nextdocker


Enter fullscreen mode Exit fullscreen mode

and create your app using the following options

Next js and Docker

Then, you can open the folder with the IDE you want.

Run npm run dev to run your Next.js app.

Next js and Docker

And if you visit localhost:3000, you will see the Next.js app running.

Next js and Docker

Dockerize the Next.js app

Now, we can dockerize the Next.js app.

Open the file called next.config.js and replace the content with this:



/** @type {import('next').NextConfig} */
const nextConfig = {
  output: 'standalone'
}

module.exports = nextConfig


Enter fullscreen mode Exit fullscreen mode

.dockerignore

Create a file called .dockerignore and add this content:



Dockerfile
.dockerignore
node_modules
npm-debug.log
README.md
.next
.git


Enter fullscreen mode Exit fullscreen mode

This is needed to avoid copying the node_modules folder to the Docker image.

In case you want an explanation, go here

Dockerfile

At the root of the project, create a file called Dockerfile and add this content:



FROM node:18-alpine AS base

# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN \
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; \
  elif [ -f package-lock.json ]; then npm ci; \
  elif [ -f pnpm-lock.yaml ]; then yarn global add pnpm && pnpm i --frozen-lockfile; \
  else echo "Lockfile not found." && exit 1; \
  fi


# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN yarn build

# If using npm comment out above and use below instead
# RUN npm run build

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "server.js"]


Enter fullscreen mode Exit fullscreen mode

In case you want an explanation, go here

Docker compose

Create a file called docker-compose.yml and add this content:



version: '3.9'

services:
  nextapp:
    container_name: nextapp
    image: nextapp
    build: .
    ports:
      - "3000:3000"


Enter fullscreen mode Exit fullscreen mode

In case you want an explanation, go here

Build the Docker Image and run the service

Build the Docker image:



docker compose build


Enter fullscreen mode Exit fullscreen mode

Then run the services



docker compose up 


Enter fullscreen mode Exit fullscreen mode

And you should see something like this

Next js and Docker

If you visit localhost:3000 you will see the Next.js app running (but this time using Docker)

Next js and Docker

Livecycle

As a final test, I want to try Livecycle to deploy the app.

You can download the LiveCycle extension on Docker Desktop

Next js and Docker

When your app is running locally, you can just use Docker Desktop to turn it on.

Next js and Docker

It's super effective!

Considerations:

  • Docker is a technology that can work on ANY application, including Next.js, of course.
  • Next.js has a super cool way to deploy applications to make Docker ALMOST useless.
  • Having Next.js running in a Docker container provides better security and dependability, faster and easier deployment procedures, and simpler application management.
  • If you already have many Docker containers running, adding a new one is easier than using the Next.js deployment procedure (Vercel) to have complete DevOps control.
  • If you have ONLY one Next.js application, I would suggest using the Next.js deployment procedure (Vercel).

So, do you need to use Docker with Next.js? Usually NOT, but it starts to make sense if you have multiple services running (and you use a tool like Livecycle).

This makes us think about how Docker is powerful. Docker doesn't care about the technology you use. It just works. With Docker, you can deploy ANY application, which is super powerful.

Kudos to Vercel for making the Next.js app deployment so easy, but I think Docker is still a great tool.

If you prefer a video version:

All the codes are available for free on GitHub (link in video description).

If you have any comment or questions, drop them below

Bye

Francesco

Top comments (26)

Collapse
 
mjoycemilburn profile image
MartinJ

Thanks for this. I've used Vercel 's deployment procedure myself and echo your thoughts on its excellence. My problem is that I've a big investment in Google Cloud hosting and don't want to switch. So, just now, if I wanted to use Next.js (which I do), I'd be a customer of the Docker intricacies that you describe so well.

But recently I've been looking at Svelte where to my amazement that I can use an "adapter" to build and deploy a Docker container to Google Cloud Run with just two commands.

I'm left wondering why Next.js have made things so difficult in this area.

Collapse
 
brianmcbride profile image
Brian McBride

You are wondering why a company that sells hosting services has made an open source platform that they manage easier to deploy on their platform, yet harder on others?

How about the features that only work on Vercel deployments?

I think it is pretty easy to see the "why" here. But just in case, I can represent it with one character: $

Collapse
 
francescoxx profile image
Francesco Ciulla

This is not a surprise to me, they are here for the money and it's fine. but for sure it's not the only way to deploy a frontend js app.

Collapse
 
mjoycemilburn profile image
MartinJ • Edited

Yes, I had the same thought - just didn't like to say it! But if this is really the case, who can one blame them? As Elon Musk would say - "I've got bills to pay"

Collapse
 
preciousnwaoha profile image
Precious Nwaoha

Not sure about this - compare yourself.
youtu.be/KNeJI61QVqg?si=UZvJwAhYid...

Collapse
 
royra profile image
Roy Razon

To me the Docker approach makes more sense if you have more than a single service, or some persistence engine like a DB or Redis.

Collapse
 
francescoxx profile image
Francesco Ciulla

same here

Collapse
 
brianmcbride profile image
Brian McBride

My experience using Astro over the last few months is a breath of fresh air compared to Vercel's Next.js.

Part of my motivation to move away from Next.js was due to features that felt like a Vercel vendor-lockin. Financially, Vercel is fine for the individual, but their pricing scales poorly in enterprise. Most larger companies also have their cloud provider in place and don't want to take on another. While you can containerize Next.js like any other app, some features won't work like they do on Vercel.

Beyond that, there are serious concerns with Next.js. In the past, I've had Next.js building modify my tsconfig files. I find it a bit shocking to have a framework modify setup/config files without asking first. I've also discovered that the React installed isn't the same as that runs in the Next.js runtime. Moreso, it was a beta version of React.

I feel strongly that libs shouldn't adjust config files and should run the versions we pin in our package.json files.

That drove me to Astro where, once past the learning curve, I found myself enjoying front-end dev a lot more.

Collapse
 
francescoxx profile image
Francesco Ciulla

maybe I should make a video on Astro with Docker, too

Collapse
 
kubilayozisik profile image
Kubilay Özışık

Thank you for the article. I have a middleware in my app and it looks like this image doesn't support it. I am doing some redirections and rewrites. Any idea how to solve it?

Failed to proxy http://localhost:3000/site Error: socket hang up
at connResetException (node:internal/errors:720:14)
at Socket.socketCloseListener (node:_http_client:474:25)
at Socket.emit (node:events:529:35)
at TCP.<anonymous> (node:net:350:12)
at TCP.callbackTrampoline (node:internal/async_hooks:128:17) {
code: 'ECONNRESET'
}

Collapse
 
pradumnasaraf profile image
Pradumna Saraf

Awesome blog, @francescoxx 👏👏

Collapse
 
francescoxx profile image
Francesco Ciulla

let's go @pradumnasaraf

Collapse
 
mhm13dev profile image
Mubashir Hassan

Has anyone tried to deploy Next.js 14 Docker Image on AWS ECS? Do you face any errors after deployment?

Collapse
 
francescoxx profile image
Francesco Ciulla

not yet, but it should be fine.

Collapse
 
mhm13dev profile image
Mubashir Hassan • Edited

After the deployment is complete, I get error cannot resolve hostname

Only happens on versions > Next 13.4

For older it works fine.

Collapse
 
cb2023 profile image
Charles Brown

Hello Francesco Ciulla,

Thank you for the comprehensive guide on deploying Next.js with Docker. The code snippets are valuable, but providing explanations for each segment and offering insights into when to use specific configurations would enhance the tutorial's clarity. Including considerations on when this approach is most suitable would be especially helpful for readers seeking guidance on decision-making.

Thank you

Collapse
 
francescoxx profile image
Francesco Ciulla

a video about dockerfile is coming on youtube this week.

Collapse
 
shricodev profile image
Shrijal Acharya

Well explained. Great blog, @francescoxx ! 🎉🎉

Collapse
 
francescoxx profile image
Francesco Ciulla

you are welcome

Collapse
 
ajackti profile image
DangTrong

Your guide is so helpful. But I want to import variables, which way can I do it? Thank you.

Collapse
 
francescoxx profile image
Francesco Ciulla

Thanks for the feedback! 😊 If you want to import environment variables in your Next.js app with Docker, you can add them to a .env file and ensure they're available in both your app and Docker container. In Next.js, make sure variables you want to access in the frontend are prefixed with NEXT_PUBLIC_. When using Docker, you can pass these variables with a docker-compose.yml file or directly in the Dockerfile. Let me know if you need more details!

Collapse
 
bullbiased profile image
Bull

Awesome.

Collapse
 
francescoxx profile image
Francesco Ciulla

thank you!