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, 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.
- The running access port needs to be mapped out.
- After completion or manual stop (Ctrl+C), the Docker container should be stopped and removed.
Edit Command to Set Environment Variables#
Add the following function to the .zshrc or .bashrc file (in the Mac environment) 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 to verify if it works by initializing a Bun project:
bun init
🎉 No issues! The project can be created and initialized normally! Next, let's try creating a server and mapping port 3001. Since the Bun environment runs inside a 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.
Let's add a piece of official demo code to the index.ts
in 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!