NGINX Unit

Express Apps§

To run your Express apps in Unit:

  1. Install Unit with the appropriate Node.js language module version.

  2. If you haven’t already done so, create your Express app and store it as usual.

  3. Next, you need to have the unit-http package installed. If it’s global, symlink it in your project directory:

    # npm link unit-http
    
  4. In your app, create a custom HTTP server (note createServer, ServerResponse, and IncomingMessage):

    #!/usr/bin/env node
    
    const {
      createServer,
      IncomingMessage,
      ServerResponse,
    } = require('unit-http')
    
    require('http').ServerResponse = ServerResponse
    require('http').IncomingMessage = IncomingMessage
    
    const express = require('express')
    const app = express()
    
    app.get('/', (req, res) => res.send('Hello, Unit!'))
    
    createServer(app).listen()
    
  5. Prepare Unit configuration for your update. To obtain an initial template, query the control API:

    # curl --unix-socket /path/to/control.unit.sock \
           http://localhost/config/ > config.json
    

    Note

    Control socket path may vary; run unitd --help or see Startup for details.

    This creates a JSON file with Unit’s current settings; update it with your project settings as follows.

  6. Edit the JSON file, adding a listener in listeners and pointing it to your app’s .js file in applications. Your project and apps will run on the listener’s IP and port at their respective URL paths.

    {
        "listeners": {
            "127.0.0.1:8080": {
                "pass": "applications/express_app"
            }
        },
    
        "applications": {
            "express_app": {
                "type": "external",
                "working_directory": "/path/to/express/app/",
                "executable": "app.js"
            }
        }
    }
    
  7. Upload the updated configuration:

    # curl -X PUT --data-binary @config.json --unix-socket \
           /path/to/control.unit.sock http://localhost/config
    

    After a successful update, your app should be available on the listener’s IP address and port:

    $ curl 127.0.0.1:8080/