Skip to content

Deploying a Hapi App

Hapi is a rich and powerful web framework for Node.js, designed for building robust, scalable, and secure applications. It offers a comprehensive plugin system, built-in input validation, and fine-grained configuration, making it a great choice for enterprise-grade APIs and services.

This guide explains how to deploy a Hapi application to Klutch.sh, both with and without a Dockerfile. It also covers installation and provides sample code to get started.

Prerequisites

  • Node.js 18+
  • Git and GitHub account
  • Klutch.sh account

Getting Started: Install Hapi

  1. Create a new directory for your app and initialize npm:
    Terminal window
    mkdir my-hapi-app
    cd my-hapi-app
    npm init -y
  2. Install Hapi:
    Terminal window
    npm install @hapi/hapi
  3. Create a basic Hapi app (index.js):
    const Hapi = require('@hapi/hapi');
    const port = process.env.PORT || 3000;
    const init = async () => {
    const server = Hapi.server({
    port,
    host: '0.0.0.0'
    });
    server.route({
    method: 'GET',
    path: '/',
    handler: () => 'Hello from Hapi on Klutch.sh!'
    });
    await server.start();
    console.log(`Server running on port ${port}`);
    };
    init();
  4. Add a start script in your package.json:
    "scripts": {
    "start": "node index.js"
    }
  5. Test locally:
    Terminal window
    npm start
    Visit http://localhost:3000 to see your app running.

Deploying Without a Dockerfile

  1. Push your Hapi app to a GitHub repository.
  2. Log in to Klutch.sh.
  3. Create a new project and give it a name.
  4. Create a new app:
    • Select your Hapi GitHub repository and branch
    • Set the port to route traffic (usually 3000 for Hapi)
    • Choose region, compute, number of instances, and add any environment variables
  5. Add a start script in your package.json as shown above.
  6. Click “Create” to deploy. Klutch.sh will build and deploy your app automatically.

Deploying With a Dockerfile

  1. Add a Dockerfile to your project root. Example:
    # Use official Node.js image
    FROM node:18-alpine
    # Set working directory
    WORKDIR /app
    # Copy package files and install dependencies
    COPY package*.json ./
    RUN npm install --production
    # Copy app source
    COPY . .
    # Expose port (match your Hapi app)
    EXPOSE 3000
    # Start the app
    CMD ["npm", "start"]
  2. Push your code (with Dockerfile) to GitHub.
  3. In Klutch.sh, follow the same steps to create a project and app, but select the Dockerfile option when prompted.
  4. Set the service details and environment variables as needed.
  5. Click “Create” to deploy. Klutch.sh will build your Docker image and deploy your app.

Note: Your Hapi app should always listen on the PORT environment variable as shown above.


Resources


Deploying to Klutch.sh is simple and flexible. Choose the method that best fits your workflow and project requirements.