Jakho

Jakho

Full Stack developer.
x

Deploying Bun Environment with Docker

Recently, I developed a small tool using Bun. During the process, I felt that installing Bun might pollute my local environment, as these rapidly evolving tools update frequently. I don't like having to uninstall or upgrade after installation. So, with some research and the help of AI, I deployed the Bun.js environment on my local machine using Docker.

Install Docker#

I am using a Mac device, so I installed Docker Desktop for easier management of Docker applications, which can be downloaded from the official website.

Pull Bun's Image#

If using the command line:

docker pull oven/bun

Using the graphical interface:
image

Pull the oven/bun image.

Requirements#

  • The Bun project files should be stored on the local machine rather than in Docker.
  • The running access port needs to be mapped out.
  • After running or manually stopping (Ctrl+C), the Docker container should be stopped and deleted.

Edit Command to Set Environment Variables#

Add the following function to the .zshrc or .bashrc (in Mac environment) file to avoid writing a long string of commands every time you run it. Remember to save and source it to make it effective.

bun() {
  local port=${1:-8080}
  # Add --init parameter to ensure Docker container handles signals correctly (like Ctrl+C),
  # it will run an init process inside the container as PID 1,
  # which can correctly forward signals to the application.
  if [[ $1 =~ ^[0-9]+$ ]]; then
    docker run -it --rm -w /app -v "$(pwd)":/app -p ${port}:${port} --init oven/bun bun "${@:2}"
  else
    docker run -it --rm -w /app -v "$(pwd)":/app -p 8080:8080 --init oven/bun bun "$@"
  fi
}

Usage#

We can try initializing a Bun project to verify if it works:

bun init

image

🎉 No problem! The project can be created and initialized successfully! Next, let's try creating a server and mapping port 3001. Since the Bun environment is still running inside the Docker container, we need to map the host's port 3001 to the container's port 3001. As mentioned above, there's no need to set this up again because the command we set in the environment variable has already taken care of it; we just need to write the port number we want to map into the run command.

We will add a piece of official demo code to the index.ts of the Bun project we just initialized:

const server = Bun.serve({
  port: 3001,
  fetch(request) {
    return new Response("Welcome to Bun!");
  },
});
console.log(`Listening on localhost:${server.port}`);

Then run the command with the port number:

bun 3001 run index.ts

image

Access the local machine's port 3001:

image

🎉 Mission accomplished!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.