NGINX Unit
v. 1.25.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 install express --save
    # npm link unit-http
    
  3. Create your Express app; let’s store it as /path/to/app/app.js. First, initialize the directory:

    $ cd /path/to/app/
    $ npm init
    

    Next, add your application code:

    #!/usr/bin/env node
    
    const http = require('http')
    const express = require('express')
    const app = express()
    
    app.get('/', (req, res) => res.send('Hello, Express on Unit!'))
    
    http.createServer(app).listen()
    

    The file should be made executable so the application can run on Unit:

    $ chmod +x app.js
    
  4. Run the following command so Unit can access the application directory:

    # 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": "/usr/bin/env",
                "arguments": [
                    "node",
                    "--loader",
                    "unit-http/loader.mjs",
                    "--require",
                    "unit-http/loader",
                    "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