Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 39 ยท Deploy and Compatibility

Docker and Single-File Executables

Ship a Bun app: a multi-stage Dockerfile with the official image, frozen lockfile installs, non-root users, compile to one executable with bun build --compile, cross-targets and deployment checklists.

An app is only useful once it runs somewhere other than your laptop. Bun gives you two good ways to ship: a container image (the standard for cloud hosting), or a single executable file that bundles your code and the Bun runtime so the target machine needs nothing installed. This lesson shows both, with the choices that matter for production.

Docker and Bun are not available in this site's runners, so all Dockerfiles and commands here are read-only. The runnable TryIt checks a few deployment decisions (configuration parsing and a health endpoint) with plain Node.

Preparing the app

Before packaging, make sure the app is configured through the environment and has a health endpoint:

TypeScript
// src/index.ts
const port = Number(Bun.env.PORT ?? 3000);

const server = Bun.serve({
  port,
  routes: {
    "/health": () => Response.json({ status: "ok", uptime: process.uptime() }),
    "/": () => new Response("Hello from production"),
  },
});

console.log(`listening on ${server.url}`);

Set NODE_ENV=production in production: Bun then turns off the development error pages, and many libraries enable optimizations. Add a .dockerignore so you never copy dependencies or secrets into the build context:

TEXT
node_modules
.git
.env
.env.*
*.log
dist

A Dockerfile with the official image

The official image oven/bun is published in several flavors (Debian default, -slim, -alpine, -distroless). A good production Dockerfile uses stages, so dev dependencies and build tools stay out of the final image:

DOCKERFILE
# syntax=docker/dockerfile:1
FROM oven/bun:1 AS base
WORKDIR /app

# 1) install ALL dependencies (cached while the lockfile is unchanged)
FROM base AS install
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile

# 2) install ONLY production dependencies for the final image
FROM base AS prod-deps
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile --production

# 3) optional: build step (type check, bundle)
FROM install AS build
COPY . .
RUN bun test && bun run build

# 4) the final, small image
FROM base AS release
ENV NODE_ENV=production
COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/src ./src
COPY package.json .

USER bun
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD bun -e "fetch('http://localhost:3000/health').then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
CMD ["bun", "run", "src/index.ts"]

Why these choices:

  • COPY package.json bun.lock before the code means Docker re-runs bun install only when dependencies change; editing a source file reuses the cached layer.
  • --frozen-lockfile fails the build if the lockfile and package.json disagree, so the image has exactly the versions you tested. --production skips devDependencies.
  • USER bun runs as an unprivileged user that exists in the official image. If an attacker finds a bug, they are not root inside the container.
  • No build for TypeScript is needed: Bun runs .ts directly. If you bundle (bun build), run the output instead.
  • Exec-form CMD ["bun", ...] makes Bun PID 1, so it receives SIGTERM when the container stops and can shut down cleanly (see the next lesson).

Build and run:

TEXT
docker build -t myapp:1.0 .
docker run --rm -p 3000:3000 -e NODE_ENV=production -e DATABASE_URL=... myapp:1.0

Pass secrets at run time through environment variables or your platform's secret store. Never bake them into the image with ENV or COPY .env.

Persisting data

A container's file system disappears when the container is replaced. If you use SQLite (bun:sqlite), mount a volume and point the database at it:

TEXT
docker run -v appdata:/data -e DB_PATH=/data/app.db -p 3000:3000 myapp:1.0

With WAL mode, run one instance writing to that file. For several instances, use a client-server database.

Single-file executables

bun build --compile bundles your entry file, its dependencies and a copy of the Bun runtime into one binary:

TEXT
bun build --compile --minify ./src/index.ts --outfile myapp
./myapp

The resulting myapp (or myapp.exe on Windows) runs on a machine with no Bun and no node_modules. It is ideal for CLI tools you give to other people, small self-hosted services and installers. Options worth knowing:

TEXT
--target=bun-linux-x64        # cross-compile: also bun-linux-arm64, bun-darwin-arm64,
                              #   bun-darwin-x64, bun-windows-x64, bun-linux-x64-musl
--minify                      # smaller output
--sourcemap                   # readable stack traces
--bytecode                    # precompile to bytecode: faster startup, bigger file
--env BUN_PUBLIC_*            # inline selected environment variables at build time

You can build for every platform from one machine, so a CI job can publish downloads for Linux, macOS and Windows. Expect a file of tens of megabytes, because it contains the runtime. To embed assets such as templates, import them with an attribute:

TypeScript
import logo from "./logo.png" with { type: "file" };
const bytes = await Bun.file(logo).bytes(); // works inside the compiled binary

Config that must differ per machine should still come from environment variables or a file next to the executable, not from build time. Smoke-test a compiled binary on a clean machine (or a bare container such as debian:stable-slim), because missing system libraries on the target are the usual surprise. A compiled executable can be copied into a very small image:

DOCKERFILE
FROM oven/bun:1 AS build
WORKDIR /app
COPY . .
RUN bun install --frozen-lockfile && bun build --compile --minify src/index.ts --outfile server

FROM debian:stable-slim
COPY --from=build /app/server /usr/local/bin/server
USER nobody
CMD ["server"]

Other places to run Bun

  • A plain server (VPS): install Bun, copy the app, run it under systemd with Restart=always, and put nginx or Caddy in front for HTTPS and compression.
  • Platform services such as Railway, Render, Fly.io and many container hosts run the Docker image. Some platforms (for example Vercel) offer Bun as a selectable runtime or build option; check their current documentation.
  • Serverless functions work when the platform supports Bun or custom containers; cold-start time is short because Bun starts quickly.

Check the configuration logic

The runnable block below tests the kind of startup code that decides whether a deployment works: reading the port, validating required variables and shaping a health response.

Node.js Config validation for deployments (plain Node)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Failing at startup with a clear message is much better than a container that starts and then breaks on its first request.

Deployment checklist

  • bun install --frozen-lockfile in CI and in Docker.
  • NODE_ENV=production, secrets from the platform, no .env in the image.
  • Run as a non-root user; expose only the needed port.
  • /health endpoint plus a container health check.
  • Graceful shutdown on SIGTERM (next lesson).
  • Logs to stdout/stderr as one JSON object per line; let the platform collect them.
  • A rollback plan: keep the previous image tag.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why copy package.json and bun.lock and run bun install before copying the source code in a Dockerfile?

    Layer caching: unchanged dependency files mean the slow install step is reused.
  2. 2. What does bun install --frozen-lockfile do?

    It guarantees reproducible installs; --production is the flag that skips devDependencies.
  3. 3. What does bun build --compile produce?

    The binary runs without Bun or node_modules installed on the target.
  4. 4. Why use USER bun in the Dockerfile?

    Least privilege: a compromised process should not be root.

Summary

  • Configure by environment variables; add /health; set NODE_ENV=production.
  • Multi-stage Dockerfiles on oven/bun: cached dependency layer, --frozen-lockfile, --production, USER bun, exec-form CMD.
  • Keep secrets out of images; use volumes for SQLite files.
  • bun build --compile (with --target, --minify, --bytecode) makes a single portable executable, even cross-platform.
  • Use a checklist: reproducible install, non-root, health checks, graceful shutdown, logs to stdout, rollback.

Next: Production Hardening, Workers and Performance