Skip to content

Conversation

@soltrinox
Copy link

Added Docker-based Rust CLI Example for Vercel Deployment

Overview

This PR introduces a comprehensive Docker-based Rust CLI example (examples/docker-build/) that demonstrates how to deploy Rust binaries to Vercel's serverless environment using Docker for cross-platform compilation. This example provides a complete, production-ready template for developers who want to leverage Rust's performance in serverless deployments.

🚀 Key Features

Complete Docker Build Pipeline

  • Multi-stage Dockerfile with optimized dependency caching
  • Cross-platform compilation using cargo-zigbuild + Zig
  • Static linking with musl target for Vercel compatibility
  • Automated binary extraction and deployment preparation

Comprehensive Build System

  • Multiple build strategies: Local Rust toolchain, Docker, or hybrid approaches
  • Automated deployment script (build-and-deploy.sh) with full validation
  • Cross-platform support for macOS, Linux, and Windows development
  • Verbose logging and error handling throughout the pipeline

Interactive Frontend

  • Modern Next.js 15 application with Tailwind CSS
  • Ping/Pong functionality to test Rust binary connectivity
  • Custom message processing with real-time JSON responses
  • Responsive design with gradient backgrounds and smooth animations

Production-Ready Architecture

  • Serverless function proxy (api/proxy.js) for binary communication
  • JSON-based communication between frontend and Rust binary
  • Error handling and timeout management
  • Vercel configuration optimized for binary deployment

📁 Project Structure

examples/docker-build/
├── api/
│   ├── proxy.js          # Vercel serverless function
│   └── bin/cli           # Compiled Rust binary (generated)
├── rust-cli/
│   ├── Cargo.toml        # Rust dependencies
│   └── src/main.rs       # Rust CLI with ping/echo logic
├── scripts/
│   ├── build-and-deploy.sh      # Complete automation script
│   ├── build-cli-docker.sh      # Docker build script
│   ├── build-cli.sh             # Local build script
│   └── validate-docker-build.sh # Validation script
├── docker/
│   └── cli.Dockerfile    # Multi-stage Docker build
├── pages/
│   ├── index.js          # Interactive frontend
│   └── _app.js           # Next.js app wrapper
├── Dockerfile            # Main Docker build
├── vercel.json           # Vercel configuration
├── package.json          # Node.js dependencies
└── README.md             # Comprehensive documentation

🔧 Technical Implementation

Docker Build Process

The example uses a sophisticated multi-stage Docker build:

  1. Builder Stage: Uses ghcr.io/messense/cargo-zigbuild:latest for cross-compilation
  2. Dependency Caching: Copies Cargo.toml first for optimal layer caching
  3. Source Compilation: Replaces dummy source with actual code
  4. Export Stage: Creates minimal image with only the compiled binary

Rust CLI Implementation

  • JSON-based I/O: Structured communication via stdin/stdout
  • Ping/Pong Protocol: Built-in health check functionality
  • Error Handling: Comprehensive error management with anyhow
  • Static Linking: musl target for zero external dependencies

Frontend Integration

  • Real-time Communication: Fetch API for binary interaction
  • Interactive UI: Ping test and custom message processing
  • Error Display: User-friendly error messages and loading states
  • Responsive Design: Mobile-first approach with Tailwind CSS

🛠️ Build & Deployment Options

Option 1: Docker Build (Recommended)

npm run build:cli:docker  # Build Rust binary with Docker
npm run build            # Build Next.js application
vercel --prod            # Deploy to Vercel

Option 2: Local Rust Toolchain

npm run build:cli        # Build with local Rust + cross-compilation
npm run build           # Build Next.js application
vercel --prod           # Deploy to Vercel

Option 3: Automated Pipeline

npm run build:deploy    # Complete build and deployment in one command

📋 Prerequisites & Setup

The example supports multiple development environments:

Core Dependencies

  • Node.js 22.x (specified in package.json engines)
  • Package Manager: npm or yarn
  • Git (for Vercel CLI authentication)

Rust Compilation Options

  • Option A: Local Rust + cross-compilation tools (cargo-zigbuild + Zig)
  • Option B: Docker (no local Rust required)

Platform-Specific Installation

  • macOS: Homebrew-based installation scripts
  • Linux: APT-based installation scripts
  • Cross-platform: Docker-based builds

🎯 Use Cases & Benefits

Perfect For

  • Data Processing: High-performance data manipulation in serverless
  • Image Processing: Rust-based image manipulation utilities
  • Cryptographic Functions: Secure computation in serverless environment
  • Custom CLI Tools: Any Rust-based command-line application

Key Benefits

  • Zero Infrastructure Management: Vercel handles all scaling and deployment
  • Cross-Platform Compatibility: Docker ensures consistent builds
  • Performance at Scale: Rust's speed with serverless scalability
  • Easy Customization: Clear separation of concerns for modification

📚 Documentation

The example includes comprehensive documentation:

  • Detailed README: 1,274 lines covering all aspects
  • Installation guides: Platform-specific setup instructions
  • Customization examples: Code samples for common modifications
  • Troubleshooting section: Common issues and solutions
  • Docker validation: Complete validation process documentation

🔍 Validation & Testing

Docker Build Validation

  • ✅ Multi-stage build process
  • ✅ Binary extraction and permissions
  • ✅ Linux ELF 64-bit executable generation
  • ✅ Static linking verification
  • ✅ Vercel compatibility testing

Automated Testing

  • ✅ Prerequisites validation
  • ✅ Build process verification
  • ✅ Binary functionality testing
  • ✅ Deployment pipeline validation

🚀 Quick Start

# Clone and setup
git clone <repo-url>
cd examples/docker-build
npm install

# Build and deploy
npm run build:deploy

# Test the deployment
# Visit your Vercel URL and click "Ping Rust Binary"

💡 Innovation Highlights

  1. Hybrid Build Strategy: Supports both local and Docker-based compilation
  2. Comprehensive Automation: Single-command build and deployment
  3. Production-Ready: Includes error handling, validation, and monitoring
  4. Developer Experience: Detailed logging, verbose output, and clear error messages
  5. Cross-Platform: Works seamlessly across macOS, Linux, and Windows

🎉 Impact

This example provides developers with:

  • A complete template for Rust serverless deployment
  • Best practices for Docker-based cross-compilation
  • Production-ready code with comprehensive error handling
  • Educational value through detailed documentation and examples
  • Immediate usability with minimal setup requirements

The docker-build example represents a significant addition to the Vercel Rust ecosystem, providing developers with a robust, well-documented template for deploying high-performance Rust applications to serverless environments.


Files Added: 15+ new files including Docker configuration, build scripts, Rust CLI, Next.js frontend, and comprehensive documentation
Lines of Code: ~2,000+ lines across Rust, JavaScript, Docker, and documentation
Documentation: 1,274-line comprehensive README with examples and troubleshooting

- Introduced Docker build process for compiling Rust CLI binaries.
- Added .dockerignore, .gitignore, and .vercelignore files to manage build context and deployment.
- Created Dockerfile for multi-stage builds, ensuring a minimal final image.
- Implemented scripts for building and deploying the Rust CLI.
- Integrated a Next.js frontend to interact with the Rust binary via API.
- Added validation scripts to ensure Docker build integrity and binary functionality.
- Updated README with detailed instructions for setup and usage.
…flow

- Expanded prerequisites section for local development and deployment.
- Added platform-specific installation instructions for macOS and Linux.
- Included a comprehensive quick start guide for cloning, building, and deploying the project.
- Enhanced the architecture overview and added a deployment flow diagram for clarity.
- Updated troubleshooting section with common issues and solutions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant