Here are some best practices for using Bun in a multi-stage Docker build:
Use a Separate Install Step
Separate the installation of dependencies from copying your application code. This allows Docker to cache the dependency installation layer and only rebuild it when the dependencies change.
dockerfile
FROM oven/bun AS build
WORKDIR /app
# Copy the lock file and install dependencies
COPY bun.lockb package.json .
RUN bun install --frozen-lockfile
# Copy the application code
COPY . .
Use Multi-Stage Builds for Smaller Images
Leverage multi-stage builds to create a smaller final image. Compile your application into a standalone executable in the build stage, then copy just the executable into a smaller base image for the final stage.
dockerfile
# Build stage
FROM oven/bun AS build
WORKDIR /app
# Copy dependencies and install
COPY bun.lockb package.json .
RUN bun install --frozen-lockfile
# Copy source and compile
COPY . .
RUN bun build ./src --compile --outfile myapp
# Final stage
FROM ubuntu:22.04
WORKDIR /app
# Copy the compiled executable from the build stage
COPY --from=build /app/myapp .
CMD ["./myapp"]
Use .dockerignore
Create a `.dockerignore` file to exclude unnecessary files from being copied into the Docker image. This can significantly reduce build times and image sizes.
node_modules
.git
Use Bun's Optimized Docker Image
Use the official `oven/bun` Docker image provided by Bun. This image is optimized for running Bun applications and includes the necessary dependencies.
dockerfile
FROM oven/bun
Specify the Target Platform
When cross-compiling for a different platform, explicitly specify the target platform using the `--target` flag with `bun build`.
dockerfile
RUN bun build --compile --target=bun-linux-x64 ./src --outfile myapp
Avoid Alpine for ARM64
If building for ARM64, avoid using Alpine Linux as the base image. Alpine uses musl libc which is not compatible with Bun's ARM64 builds. Use a Debian-based image instead.
dockerfile
FROM ubuntu:22.04
By following these best practices, you can create efficient and optimized Docker images for deploying Bun applications.
Citations:[1] https://dev.to/code42cate/how-to-dockerize-a-bun-app-38e4
[2] https://andrekoenig.de/articles/using-bun-as-the-package-manager-in-production-ready-docker-images
[3] https://www.koyeb.com/docs/deploy/bun
[4] https://bun.sh/blog/bun-v1.0
[5] https://github.com/oven-sh/bun/discussions/1040
[6] https://bun.sh/docs/installation
[7] https://dev.to/clerijr/your-first-api-with-bun-express-and-prisma-p90
[8] https://bun.sh/docs/bundler/executables