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 get updated frequently. I don't like having to uninstall or upgrade after installation. So, after some research and with 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:
Pull the oven/bun
image.
Requirements#
- The Bun project files should be stored on the local machine, not in Docker.
- It should be able to map the access port after running.
- After finishing 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 the 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 allow Docker container to handle 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 to verify if it works by initializing a Bun project:
bun init
🎉 No problem! The project can be created and initialized normally! Next, let's try to create a server and map port 3001. Since the Bun environment is still running in the Docker container, we need to map the host's port 3001 to the container's port 3001. As mentioned above, there is 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 running 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
Access the local machine's port 3001:
🎉 Mission accomplished!