By Tom Snelling
Published 7th July 2022
Bun is a new JavaScript runtime that boasts impressive performance improvements over Node.js. It’s a runtime, bundler, transpiler, and package manager, all in one.
In this guide, we’ll cover how to deploy an application using the Bun runtime & Bun’s built-in HTTP server to the cloud using Northflank. Northflank is a self-service developer platform that makes it simple to deploy applications to the cloud. They provide a free developer sandbox you can use to follow along with this tutorial.
The full source code for this guide can be found in this GitHub repository.
Or, for the fastest way to deploy a Bun app, you can use the Northflank Bun template to deploy your Bun app in 1 click:
For this guide, we will simply use the built-in HTTP server that Bun provides to create a single endpoint we can query. This endpoint will just return a message containing the current time and the path that the request was made to.
To use Bun's built in HTTP server, all we have to do is export a default object that contains a fetch function. Optionally, we can supply a port attribute to run the server on a specific port.
index.js
import moment from 'moment';
export default {
port: 3000,
fetch(req) {
const url = new URL(req.url);
const now = moment().format('YYYY-MM-DD HH:mm:ss');
return new Response(`Hello from bun on Northflank!\nThe time is ${now}.\nThis is ${url.pathname}.`);
}
};
As long as we have Bun installed, we can run this in more or less the same way we would run a Node.js script — just with bun index.js
(rather than node index.js
).
To deploy our app on Northflank, we need to write a Dockerfile. Bun provides a prebuilt Docker image jarredsumner/bun:edge
that we can base off, meaning we don't need to install Bun ourselves during our build process.
Dockerfile
FROM oven/bun:1.0
WORKDIR /app
COPY package.json package.json
COPY bun.lockb bun.lockb
RUN bun install
COPY . .
EXPOSE 3000
ENTRYPOINT ["bun", "index.js"]
We copy over our index.js
and package.json
files, run the bun install
command to install our dependencies, and then expose port 3000 so that we can reach our server. Finally we tell Docker that bun index.js
is our main entrypoint command to be run.
All that's left to do is get our app deployed. Head over to Northflank, and create a new service. Select combined service as the type, and choose your new Bun repository. Select Dockerfile as the build type, and you should see your Dockerfile load. Your port will be picked up automatically based on your EXPOSE
command and added to the list of exposed ports. Once that's done, create your service.
Your application will be built and deployed from here automatically.
Once live, click the URL in the top right of the service dashboard to query your running Bun server.