Skip to main content

Deploying Bun application to Fly.io

Oct 30, 2023

Recently built an API server with Elysia and Bun to scrape meta data from any URL. Here are a few things I did to deploy the app smoothly on Fly.io in production mode.

Steps

Create a Dockerfile with necessary steps to, here is the docker file I used

FROM oven/bun AS base

# Install dependencies only when needed
FROM base AS deps
WORKDIR /app
COPY package.json bun.lockb ./
RUN bun install

# Development image, copy all the files and run the server
FROM base AS run
WORKDIR /app
# Copy files
COPY --from=deps /app/node_modules/ ./node_modules/
COPY src/ ./src/
COPY public/ ./public/
COPY .env* package.json tsconfig.json ./
RUN bun build:prod

# Set environment variables
ENV NODE_ENV=production
CMD bun run start

ENV PORT 3000
ENV HOSTNAME localhost
EXPOSE 3000

Most of the file is self explanatory, as we are just copying files and installing dependencies. The unknowns in the file are build:prod and start commands.

Looking at the project package.json scripts section, we can find the details of them

{
  "name": "@rvgpl/meta",
  "description": "An API server for retrieving meta data of web pages",
  ...
  "scripts": {
    ...
    "build:prod": "bun build --target=bun src/index.ts --outfile=dist/index.js",
    "start": "bun dist/index.js"
    ...
  }
},

we are running bun build and compiling the typescript file to javascript into the dist folder and bun start is just running the compiled javascript file from the build step.

Once you have the above things setup, you can run

flyctl launch

this will start a CLI wizard which will gather details about the app name, region to deploy and it will create a fly.toml file with the config.

commit your config file and we are all set to deploy it using

fly deploy

if everything went well the command should log the hosted app url.

If you are curious to checkout the application I deployed on Fly.io, check out the project on rvgpl/meta and the deployed url is getmetadata.fly.dev.