Optimizing Bun + Nuxt 4 Container Deployments with Docker BuildKit and Multi-stage Builds

Hello, this is Lovefield.

When deploying a Nuxt 4 and Bun application to Ubuntu or AWS servers via Docker, deployment pipelines often become an unexpected bottleneck. Changing a single line of application code can trigger a full dependency reinstall from scratch, while the final container image easily bloats past 1GB—slowing down both deployments and rollbacks.

Fortunately, Nuxt 4 (powered by Nitro) compiles everything needed for production into a self-contained .output directory. By combining Docker BuildKit cache mounts with Multi-stage Builds, you can reduce dependency installation times to just a few seconds and shrink your final image to a fraction of its original size.

In this post, we will walk through a production-ready Dockerfile pattern tailored for Bun + Nuxt 4, along with essential security and resource configurations for Ubuntu/AWS servers.

Trim the Build Context with .dockerignore

The most common cause of sluggish Docker builds is accidentally sending local node_modules, .nuxt, .output, and .git directories into the Docker daemon. Start by adding a clean .dockerignore file at the project root:

Plain Text

1

2

3

4

5

6

7

8

9

10

11

12

# .dockerignore
node_modules
.nuxt
.output
.nitro
.cache
.git
.gitignore
.env*
README.md
Dockerfile
docker-compose.yml

Keeping your build context lean immediately speeds up the initial file-transfer phase of docker build.

Multi-stage Build + BuildKit Cache Mounts

An optimized Dockerfile relies on three core principles:

  1. Layer separation: Copy package.json and bun.lock first to maximize Docker layer cache hits.

  2. BuildKit cache mounts (--mount=type=cache): Persist Bun's global package cache (/root/.bun/install/cache) across builds so that even when bun.lock changes, unchanged packages are not re-downloaded over the network.

  3. Minimal runtime stage (runner): Discard build tools, raw source files, and node_modules, copying only the compiled .output directory into the final image.

Production-Ready Dockerfile

Dockerfile

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

# syntax=docker/dockerfile:1

# ==========================================
# 1. Base Stage
# ==========================================
FROM oven/bun:1-slim AS base
WORKDIR /app

# ==========================================
# 2. Dependencies & Build Stage
# ==========================================
FROM base AS builder

# Copy lockfile and manifest first to maximize layer caching
COPY package.json bun.lock ./

# Persist Bun's download cache across builds using BuildKit
RUN --mount=type=cache,id=bun,target=/root/.bun/install/cache \
    bun install --frozen-lockfile

# Copy source code and run Nuxt 4 production build with Nitro's Bun preset
COPY . .
ENV NITRO_PRESET=bun
RUN bun run build

# ==========================================
# 3. Production Runner Stage
# ==========================================
FROM base AS runner

ENV NODE_ENV=production
ENV NITRO_HOST=0.0.0.0
ENV NITRO_PORT=3000

# Copy only the build artifact with non-root ownership (built-in 'bun' user)
COPY --from=builder --chown=bun:bun /app/.output ./.output

USER bun
EXPOSE 3000

# Zero-dependency healthcheck using Bun's native fetch API
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD bun -e "fetch('http://localhost:3000/api/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"

CMD ["bun", "run", ".output/server/index.mjs"]

Key Takeaways

  • # syntax=docker/dockerfile:1: Ensures consistent support for modern BuildKit directives like --mount=type=cache.

  • ENV NITRO_PRESET=bun: Instructs Nuxt 4's Nitro engine to emit a production bundle optimized for Bun's native Bun.serve HTTP server.

  • Dependency-free healthcheck: Slim images intentionally omit curl and wget. Instead of installing extra binaries that expand your attack surface, running a one-liner via bun -e "fetch(...)" keeps the container minimal and clean.

Building with BuildKit Enabled

While modern Docker engines enable BuildKit by default, explicitly setting the environment variable in CI/CD pipelines (such as GitHub Actions) or older Ubuntu hosts guarantees consistent caching behavior:

Shell

1

DOCKER_BUILDKIT=1 docker build -t dico-web:latest .

The first build populates the cache, and subsequent builds—even after updating dependencies in bun.lock—will breeze through the installation step in just a couple of seconds.

Production docker-compose.yml for Ubuntu & AWS

Once your image is lean, configure memory limits and log rotation when running it on Ubuntu or AWS EC2. Leaving container logs unbounded is a classic cause of silent disk-exhaustion outages in long-running servers.

YAML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

# docker-compose.yml
services:
  web:
    image: dico-web:latest
    container_name: dico-web
    restart: unless-stopped
    ports:
      - "127.0.0.1:3000:3000"
    env_file:
      - .env.production
    deploy:
      resources:
        limits:
          memory: 512M
        reservations:
          memory: 256M
    logging:
      driver: "json-file"
      options:
        max-size: "10m"
        max-file: "3"

  • 127.0.0.1:3000:3000: Binds the container strictly to localhost so external traffic can only enter through your host Nginx reverse proxy.

  • logging options: Caps container logs at 3 rotated files of 10MB each (30MB total), preventing unexpected disk-full errors.

Summary

Effective Docker optimization rarely requires complex orchestration tools—it comes down to nailing the fundamentals:

  1. Keep the build context clean with .dockerignore.

  2. Use BuildKit cache mounts to accelerate bun install.

  3. Separate build and runtime stages via Multi-stage Builds, shipping only .output.

  4. Harden production stability with a non-root user (USER bun), native healthchecks, and log rotation.

If your Nuxt 4 deployment pipeline has been feeling sluggish or your container registry bills are creeping up, applying this structure is one of the highest-leverage improvements you can make.

This article was generated by AI.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.

Practical TypeScript 5.x Type Design: Preventing Runtime Errors with satisfies and const Type Parameters

Learn how to eliminate risky type assertions (as) and prevent runtime bugs at compile time using TypeScript 5.x patterns—including the satisfies operator, const type parameters, and Discriminated Unions.

Java Script

v5.0