DEV Community

Fabian
Fabian

Posted on • Edited on

Containers

Goal:

Containerize our next.js app!

But what does containerizing even means?

Best analogy that helped me understand:

Dockerfile = recipe
Image = prepared meal
Container = meal being served

Resources:

I will be following this guide


## Next.js with standalone output

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  output: "standalone",
};

export default nextConfig;
Enter fullscreen mode Exit fullscreen mode

What problem are we solving with the above code?

Normally when we run npm run build our project folder keep everything and we get that infamous massive node_modules folder. Now imagine putting all that into your Docker Image.

What does output: "standalone" actually do?

"Standalone output (output: "standalone") makes Next.js build a self-contained output that includes only the files and dependencies needed to run the application."-1.1

In my own words, once that trimming process is done it creates a lightweight server.js file. No need for heavy next CLI tool commands; a simple:

node server.js
Enter fullscreen mode Exit fullscreen mode

to run our app and same lightweight file is used for deployments.

Docker Images

dhi.io - Docker Hardened Images (DHIs). They are base images pre-configured, patched and scanned by Docker to strip out unnecessary software and security vulnerabilities.

we run docker login dhi.io because we have to login before being able to docker pull. The hardened images are found in Docker's private catalog.

The 3-Stage Dockerfile:

[ Stage 1: dependencies ] ──(passes node_modules)──> [ Stage 2: builder ] ──(passes standalone app)──> [ Stage 3: runner ]
 (Installs packages)                                  (Compiles Next.js)                                (Final tiny image)

Enter fullscreen mode Exit fullscreen mode

Stage 1: Download all NPM packages safely and quickly

Stage 2: Turns source code into lightweight Next.js standalone bundle.

How it works? grabs the installed node_modules from Stage 1, copies over the app code and runs npm build.

Result: Because we configured output: "standalone" in our config, Next.js creates a minimal .next/standalone folder containing only the specific code needed to run in production.

Stage 3: Turns source code into lightweight Next.js standalone bundle.

Stage 1 and Stage 2 are discarded. All we have left is public/ (static images or fonts), .next/standalone (our mini Node sever), .next/static (compiled CSS/JS assets) which are

.yaml:

The package.json version for my container environment.

Success:

Top comments (0)