NGINX Unit
v. 1.24.0

Express§

To run apps built with the Express web framework using Unit:

  1. Install Unit with the unit-dev/unit-devel package. Next, install Unit’s unit-http package:

    # npm install -g --unsafe-perm unit-http
    
  2. Create your app directory, install Express, and link unit-http:

    $ mkdir -p /path/to/app/
    $ cd /path/to/app/
    $ npm init
    $ npm install express --save
    $ npm link unit-http
    
  3. Create your Express app; let’s store it as /path/to/app/app.js. Unit requires it to be executable:

    $ touch /path/to/app/app.js
    $ chmod +x /path/to/app/app.js
    

    In the code, create a custom HTTP server (note createServer, ServerResponse, and IncomingMessage). Also, mind that Unit needs a shebang to recognize the script:

    #!/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()
    

    Note

    The same modifications apply if you use the app generator to create your app.js:

    #!/usr/bin/env node
    
    const {
      createServer,
      IncomingMessage,
      ServerResponse,
    } = require('unit-http')
    
    require('http').ServerResponse = ServerResponse
    require('http').IncomingMessage = IncomingMessage
    
    // skipping generated code
    
    createServer(app).listen()
    
  4. Run the following command for each directory containing app code or data so Unit can access it:

    # chown -R unit:unit /path/to/app/
    

    Note

    The unit:unit user-group pair is available only with official packages, Docker images, and some third-party repos. Otherwise, account names may differ; run the ps aux | grep unitd command to be sure.

    For further details, including permissions, see the security checklist.

  5. Next, prepare the Express configuration for Unit:

    {
        "listeners": {
            "*:80": {
                "pass": "applications/express"
            }
        },
    
        "applications": {
            "express": {
                "type": "external",
                "working_directory": "/path/to/app/",
                "executable": "app.js"
            }
        }
    }
    
  6. Upload the updated configuration. Assuming the JSON above was added to config.json:

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

    Note

    The control socket path may vary; run unitd -h or see Startup and Shutdown for details.

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

    Express on Unit - Welcome Screen