Bun Installation Guide

Bun is a free and open-source all-in-one JavaScript runtime and toolkit built for speed. Written in Zig and powered by JavaScriptCore, it serves as a FOSS alternative to Node.js and npm/yarn/pnpm, offering dramatically faster startup times, built-in TypeScript support, JSX transpilation, and a comprehensive toolkit including bundler, test runner, and package manager.

Development tools🟢 beginner12 min⏱️ 5-10 minutes

Bun is a free and open-source all-in-one JavaScript runtime and toolkit built for speed. Written in Zig and powered by JavaScriptCore, it serves as a FOSS alternative to Node.js and npm/yarn/pnpm, offering dramatically faster startup times, built-in TypeScript support, JSX transpilation, and a comprehensive toolkit including bundler, test runner, and package manager in a single binary.

1. Prerequisites

Hardware Requirements

  • CPU: Modern 64-bit processor (x86_64 or ARM64)
  • RAM: 256MB minimum (1GB+ recommended)
  • Storage: 50MB for Bun binary, additional for projects
  • Network: Internet connection for package installation
  • Software Requirements

  • Operating System: Linux, macOS, or Windows (via WSL2)
  • Shell: Bash, Zsh, or PowerShell for installation
  • Optional: Git for version control
  • Network Requirements

  • HTTPS: Access to npm registry and GitHub
  • Ports: Application-specific (commonly 3000, 8000)
  • 2. Supported Operating Systems

    Bun officially supports:

  • RHEL 8/9 and derivatives (CentOS Stream, Rocky Linux, AlmaLinux)
  • Debian 11/12
  • Ubuntu 20.04 LTS / 22.04 LTS / 24.04 LTS
  • Arch Linux
  • Alpine Linux 3.18+ (musl support)
  • openSUSE Leap 15.5+ / Tumbleweed
  • Fedora 38+
  • macOS 12+ (Monterey and later, Intel and Apple Silicon)
  • Windows 10/11 (via WSL2)
  • 3. Installation

    #### Linux/macOS/WSL

    bash
    # Install Bun using official script
    curl -fsSL https://bun.sh/install | bash
    
    # Add to PATH (add to ~/.bashrc or ~/.zshrc)
    export BUN_INSTALL="$HOME/.bun"
    export PATH="$BUN_INSTALL/bin:$PATH"
    
    # Reload shell configuration
    source ~/.bashrc  # or ~/.zshrc
    
    # Verify installation
    bun --version

    #### Windows (Native - Experimental)

    powershell
    # Install using PowerShell (experimental)
    powershell -c "irm bun.sh/install.ps1 | iex"
    
    # Or use WSL2 (recommended)
    wsl curl -fsSL https://bun.sh/install | bash

    Method 2: Package Managers

    #### RHEL/CentOS/Rocky Linux/AlmaLinux

    bash
    # Download latest binary
    BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
    curl -LO "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
    
    # Extract and install
    unzip bun-linux-x64.zip
    sudo mv bun-linux-x64/bun /usr/local/bin/
    sudo chmod +x /usr/local/bin/bun
    
    # Create symlinks
    sudo ln -s /usr/local/bin/bun /usr/local/bin/bunx
    
    # Verify installation
    bun --version

    #### Debian/Ubuntu

    bash
    # Method 1: Official script (recommended)
    curl -fsSL https://bun.sh/install | bash
    
    # Method 2: Manual binary installation
    BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
    wget "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
    unzip bun-linux-x64.zip
    sudo mv bun-linux-x64/bun /usr/local/bin/
    sudo chmod +x /usr/local/bin/bun
    
    # Add to PATH
    echo 'export PATH="/usr/local/bin:$PATH"' >> ~/.bashrc
    source ~/.bashrc

    #### Arch Linux

    bash
    # Install from AUR
    yay -S bun-bin
    
    # Or using paru
    paru -S bun-bin
    
    # Verify installation
    bun --version

    #### Alpine Linux

    bash
    # Install dependencies
    apk add --no-cache curl unzip
    
    # Download Bun for musl
    BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
    curl -LO "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64-musl.zip"
    
    # Extract and install
    unzip bun-linux-x64-musl.zip
    mv bun-linux-x64-musl/bun /usr/local/bin/
    chmod +x /usr/local/bin/bun
    
    # Create bunx symlink
    ln -s /usr/local/bin/bun /usr/local/bin/bunx

    #### openSUSE

    bash
    # Install via zypper (if available in future)
    # Currently use manual installation
    BUN_VERSION=$(curl -s https://api.github.com/repos/oven-sh/bun/releases/latest | grep tag_name | cut -d '"' -f 4)
    wget "https://github.com/oven-sh/bun/releases/download/${BUN_VERSION}/bun-linux-x64.zip"
    unzip bun-linux-x64.zip
    sudo mv bun-linux-x64/bun /usr/local/bin/
    sudo chmod +x /usr/local/bin/bun

    #### macOS

    bash
    # Method 1: Official script
    curl -fsSL https://bun.sh/install | bash
    
    # Method 2: Homebrew
    brew tap oven-sh/bun
    brew install bun
    
    # Method 3: MacPorts
    sudo port install bun
    
    # For Apple Silicon Macs
    arch -arm64 brew install bun

    #### Windows (WSL2)

    bash
    # Install WSL2 with Ubuntu
    wsl --install -d Ubuntu
    
    # Inside WSL2
    curl -fsSL https://bun.sh/install | bash
    source ~/.bashrc
    bun --version

    Method 3: Docker

    bash
    # Run Bun in Docker
    docker run --rm -it oven/bun:latest
    
    # Create Dockerfile for Bun app
    cat > Dockerfile << 'EOF'
    FROM oven/bun:1-alpine
    WORKDIR /app
    COPY package.json bun.lockb ./
    RUN bun install --frozen-lockfile
    COPY . .
    EXPOSE 3000
    CMD ["bun", "run", "start"]
    EOF

    4. Configuration

    Environment Configuration

    bash
    # Set Bun configuration directory
    export BUN_INSTALL="$HOME/.bun"
    export PATH="$BUN_INSTALL/bin:$PATH"
    
    # Configure runtime behavior
    export BUN_CONFIG_MAX_HTTP_HEADER_SIZE=16384
    export BUN_CONFIG_NO_CLEAR_TERMINAL_ON_RELOAD=1
    
    # Set registry mirror (for China/corporate networks)
    export BUN_CONFIG_REGISTRY="https://registry.npmjs.org/"

    Project Configuration

    Create bunfig.toml for project-specific configuration:

    toml
    # bunfig.toml
    
    # Package manager settings
    [install]
    # Use exact versions
    exact = true
    
    # Install peer dependencies
    peer = true
    
    # Install dev dependencies
    dev = true
    
    # Registry settings
    [install.registry]
    url = "https://registry.npmjs.org"
    token = "$npm_token"
    
    # Cache settings
    [install.cache]
    dir = "~/.bun/install/cache"
    disable = false
    
    # Lockfile settings
    [install.lockfile]
    save = true
    
    # Build settings
    [build]
    target = "bun"
    outdir = "./dist"
    splitting = true
    sourcemap = "external"
    
    # Test settings
    [test]
    preload = "./test/setup.ts"
    timeout = 5000

    Package.json Configuration

    json
    {
      "name": "my-bun-app",
      "version": "1.0.0",
      "type": "module",
      "scripts": {
        "start": "bun run server.ts",
        "dev": "bun --watch run server.ts",
        "build": "bun build ./src/index.ts --outdir ./dist",
        "test": "bun test",
        "format": "bunx prettier --write ."
      },
      "devDependencies": {
        "bun-types": "latest"
      },
      "peerDependencies": {
        "typescript": "^5.0.0"
      }
    }

    TypeScript Configuration

    Create tsconfig.json:

    json
    {
      "compilerOptions": {
        "lib": ["ESNext"],
        "module": "esnext",
        "target": "esnext",
        "moduleResolution": "bundler",
        "moduleDetection": "force",
        "allowImportingTsExtensions": true,
        "noEmit": true,
        "composite": true,
        "strict": true,
        "downlevelIteration": true,
        "skipLibCheck": true,
        "jsx": "react-jsx",
        "allowSyntheticDefaultImports": true,
        "forceConsistentCasingInFileNames": true,
        "allowJs": true,
        "types": [
          "bun-types"
        ]
      }
    }

    5. Service Management

    Systemd Service Configuration

    Create /etc/systemd/system/bun-app.service:

    ini
    [Unit]
    Description=Bun Application
    After=network.target
    
    [Service]
    Type=simple
    User=bunapp
    Group=bunapp
    WorkingDirectory=/opt/bun-app
    ExecStart=/usr/local/bin/bun run start
    Restart=always
    RestartSec=3
    Environment=NODE_ENV=production
    Environment=PORT=3000
    
    # Security settings
    NoNewPrivileges=true
    PrivateTmp=true
    ProtectSystem=strict
    ProtectHome=true
    ReadWritePaths=/opt/bun-app
    
    [Install]
    WantedBy=multi-user.target
    bash
    # Create bun user
    sudo useradd -r -s /bin/false -d /opt/bun-app bunapp
    
    # Set permissions
    sudo chown -R bunapp:bunapp /opt/bun-app
    
    # Enable and start service
    sudo systemctl daemon-reload
    sudo systemctl enable --now bun-app
    sudo systemctl status bun-app

    Development Server

    bash
    # Start development server with hot reload
    bun --watch run server.ts
    
    # Start with specific port
    PORT=3000 bun run server.ts
    
    # Start with debugging
    bun --inspect run server.ts
    
    # Start with performance profiling
    bun --profile run server.ts

    Process Management with PM2

    bash
    # Install PM2 globally
    bun install -g pm2
    
    # Create ecosystem file
    cat > ecosystem.config.js << 'EOF'
    module.exports = {
      apps: [{
        name: 'bun-app',
        interpreter: 'bun',
        script: 'server.ts',
        cwd: '/opt/bun-app',
        instances: 'max',
        exec_mode: 'cluster',
        env: {
          NODE_ENV: 'production',
          PORT: 3000
        },
        error_file: './logs/err.log',
        out_file: './logs/out.log',
        log_file: './logs/combined.log',
        time: true
      }]
    };
    EOF
    
    # Start with PM2
    pm2 start ecosystem.config.js
    pm2 save
    pm2 startup

    6. Troubleshooting

    Common Issues

    1. Installation failures:

    bash
    # Check system architecture
    uname -m
    
    # Download correct binary
    # x64 for Intel/AMD
    # aarch64 for ARM64
    
    # Manual installation fallback
    curl -fsSL https://bun.sh/install | bash -s "bun-v1.0.0"

    2. Package installation issues:

    bash
    # Clear cache
    bun pm cache rm
    
    # Install with verbose output
    bun install --verbose
    
    # Use different registry
    bunx --registry https://registry.npmmirror.com install

    3. Module resolution errors:

    bash
    # Check module resolution
    bun repl
    > import.meta.resolve("package-name")
    
    # Debug module loading
    BUN_DEBUG=1 bun run script.ts
    
    # Clear module cache
    rm -rf ~/.bun/install/cache

    4. Performance issues:

    bash
    # Profile application
    bun --profile run server.ts
    
    # Check memory usage
    bun --print process.memoryUsage()
    
    # Increase memory limit
    ulimit -v unlimited

    Debug Information

    bash
    # Get Bun information
    bun --version
    bun --revision
    
    # Check installation
    which bun
    ls -la ~/.bun/bin/
    
    # Environment variables
    bun --print process.env
    
    # Test JavaScript engine
    bun eval 'console.log(process.versions)'

    7. Security Considerations

    Runtime Security

    bash
    # Run with limited permissions
    bun run --no-install server.ts
    
    # Disable shell access
    bun run --no-shell server.ts
    
    # Use strict mode
    cat > server.ts << 'EOF'
    "use strict";
    
    // Application code here
    EOF

    Package Security

    bash
    # Audit dependencies
    bunx npm audit
    
    # Check for vulnerabilities
    bunx snyk test
    
    # Lock dependency versions
    bun install --frozen-lockfile
    
    # Verify package integrity
    bun pm hash

    Production Deployment

    bash
    # Create production build
    bun build ./src/index.ts \
      --target=bun \
      --minify \
      --sourcemap=external \
      --outdir=./dist
    
    # Set production environment
    export NODE_ENV=production
    
    # Disable source maps in production
    export BUN_CONFIG_DISABLE_SOURCEMAPS=1

    Secure Service Configuration

    ini
    # Enhanced systemd security
    [Service]
    # ... existing configuration ...
    
    # Security hardening
    CapabilityBoundingSet=
    SystemCallFilter=@system-service
    SystemCallErrorNumber=EPERM
    ProtectKernelTunables=true
    ProtectKernelModules=true
    ProtectControlGroups=true
    RestrictRealtime=true
    RestrictNamespaces=true
    RestrictSUIDSGID=true
    RemoveIPC=true
    PrivateDevices=true

    8. Performance Tuning

    Runtime Optimization

    bash
    # Enable JIT optimizations
    export BUN_JSC_forceJIT=1
    
    # Configure garbage collection
    export BUN_JSC_gcMaxHeapSize=2048
    
    # Use native code generation
    export BUN_JSC_useBBQJIT=1
    export BUN_JSC_useOMGJIT=1
    
    # Optimize for startup time
    export BUN_JSC_useJIT=0  # Disable JIT for faster startup

    Application Performance

    typescript
    // Use Bun's optimized APIs
    import { serve } from "bun";
    
    const server = serve({
      port: 3000,
      fetch(request) {
        return new Response("Hello from Bun!");
      },
      // Enable compression
      compression: true,
      // Set max request body size
      maxRequestBodySize: 1024 * 1024 * 10, // 10MB
    });
    
    // Use native SQLite
    import { Database } from "bun:sqlite";
    const db = new Database("mydb.sqlite");
    
    // Use Web Streams API
    const file = Bun.file("large-file.txt");
    const stream = file.stream();

    Build Optimization

    bash
    # Production build with optimizations
    bun build ./src/index.ts \
      --target=bun \
      --minify \
      --splitting \
      --external react \
      --external react-dom \
      --outdir=./dist
    
    # Bundle for browsers
    bun build ./src/browser.ts \
      --target=browser \
      --minify \
      --splitting \
      --format=esm \
      --outdir=./public

    9. Backup and Restore

    Project Backup

    bash
    #!/bin/bash
    # backup-bun-project.sh
    
    PROJECT_DIR="/opt/bun-app"
    BACKUP_DIR="/var/backups/bun"
    DATE=$(date +%Y%m%d_%H%M%S)
    
    mkdir -p $BACKUP_DIR
    
    # Backup project files
    tar -czf $BACKUP_DIR/bun_project_$DATE.tar.gz \
        -C $PROJECT_DIR \
        --exclude='node_modules' \
        --exclude='.git' \
        --exclude='dist' \
        .
    
    # Backup lockfile separately
    cp $PROJECT_DIR/bun.lockb $BACKUP_DIR/bun.lockb.$DATE
    
    echo "Project backup completed: $BACKUP_DIR/bun_project_$DATE.tar.gz"

    Dependency Management

    bash
    # Generate lockfile
    bun install --yarn
    
    # Verify lockfile integrity
    bun install --frozen-lockfile
    
    # Export dependency tree
    bun pm ls --all > dependencies.txt
    
    # Backup global packages
    bun pm ls -g > global-packages.txt

    Migration from Node.js

    bash
    #!/bin/bash
    # migrate-from-node.sh
    
    # Convert package-lock.json to bun.lockb
    bun install
    
    # Update scripts in package.json
    sed -i 's/node /bun /g' package.json
    sed -i 's/npm run/bun run/g' package.json
    sed -i 's/npx /bunx /g' package.json
    
    # Test compatibility
    bun test

    10. System Requirements

    Minimum Requirements

  • CPU: 1 core, 1.0 GHz x86_64/ARM64
  • RAM: 256MB
  • Storage: 50MB
  • OS: Linux kernel 3.10+, macOS 12+
  • CPU: 2+ cores, 2.0+ GHz
  • RAM: 1GB+
  • Storage: 1GB+ SSD
  • Network: Broadband for package downloads
  • Enterprise Requirements

  • CPU: 4+ cores, 3.0+ GHz
  • RAM: 4GB+
  • Storage: 10GB+ NVMe
  • Network: Gigabit Ethernet
  • 11. Support

    Official Resources

  • Website: https://bun.sh
  • GitHub: https://github.com/oven-sh/bun
  • Documentation: https://bun.sh/docs
  • Discord: https://bun.sh/discord
  • Community Support

  • Discord Server: https://discord.gg/CXdq2DP29u
  • GitHub Discussions: https://github.com/oven-sh/bun/discussions
  • Twitter/X: @bunjavascript
  • Stack Overflow: [bun] tag
  • 12. Contributing

    How to Contribute

    1. Fork the repository on GitHub

    2. Create a feature branch

    3. Submit pull request

    4. Follow Zig and TypeScript coding standards

    5. Include tests and benchmarks

    Development Setup

    bash
    # Clone repository
    git clone https://github.com/oven-sh/bun.git
    cd bun
    
    # Install Zig
    curl -fsSL https://ziglang.org/download/0.11.0/zig-linux-x86_64-0.11.0.tar.xz | tar xJ
    
    # Build Bun
    make setup
    make build
    
    # Run tests
    make test

    13. License

    Bun is licensed under the MIT License.

    Key points:

  • Free to use, modify, and distribute
  • Commercial use allowed
  • No warranty provided
  • Attribution required
  • 14. Acknowledgments

    Credits

  • Jarred Sumner: Creator and lead developer
  • Oven Team: Core development team
  • JavaScriptCore Team: JavaScript engine
  • Zig Community: Systems programming language
  • 15. Version History

    Recent Releases

  • v1.0.x: First stable release with production-ready features
  • v0.8.x: Added bundler and test runner
  • v0.7.x: Improved Node.js compatibility
  • Major Features by Version

  • v1.0: Production ready, stable API
  • v0.8: Built-in bundler and test runner
  • v0.6: Package manager implementation
  • 16. Appendices

    A. Quick Start Examples

    typescript
    // server.ts - HTTP server
    import { serve } from "bun";
    
    serve({
      port: 3000,
      fetch(request) {
        const url = new URL(request.url);
        
        if (url.pathname === "/") {
          return new Response("Welcome to Bun!");
        }
        
        if (url.pathname === "/json") {
          return Response.json({ message: "Hello from Bun!" });
        }
        
        return new Response("Not found", { status: 404 });
      },
    });
    
    console.log("Server running at http://localhost:3000");

    B. Testing Example

    typescript
    // math.test.ts
    import { expect, test, describe } from "bun:test";
    
    describe("math operations", () => {
      test("addition", () => {
        expect(2 + 2).toBe(4);
      });
      
      test("async test", async () => {
        const result = await Promise.resolve(42);
        expect(result).toBe(42);
      });
    });
    
    // Run tests: bun test

    C. Bundler Example

    typescript
    // build.ts
    await Bun.build({
      entrypoints: ["./src/index.ts"],
      outdir: "./dist",
      target: "browser",
      splitting: true,
      sourcemap: "external",
      minify: {
        whitespace: true,
        identifiers: true,
        syntax: true,
      },
      external: ["react", "react-dom"],
    });

    D. SQLite Example

    typescript
    // database.ts
    import { Database } from "bun:sqlite";
    
    const db = new Database("myapp.db");
    
    // Create table
    db.run(`
      CREATE TABLE IF NOT EXISTS users (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        email TEXT UNIQUE NOT NULL
      )
    `);
    
    // Insert data
    const insert = db.prepare("INSERT INTO users (name, email) VALUES (?, ?)");
    insert.run("Alice", "alice@example.com");
    
    // Query data
    const users = db.query("SELECT * FROM users").all();
    console.log(users);
    
    // Close database
    db.close();

    E. Performance Comparison

    bash
    # Benchmark script
    cat > bench.js << 'EOF'
    console.time("startup");
    console.log("Hello, World!");
    console.timeEnd("startup");
    EOF
    
    # Compare startup times
    time bun bench.js
    time node bench.js
    time deno run bench.js

    ---

    For more information and updates, visit https://github.com/howtomgr/bun