node.jsnext.js

NextJS Deployment - How can I simply deploy NextJS like NodeJS on Ubuntu server?


To deploy NodeJS, I use systemd and configure /lib/systemd/system/[service_name].service file

========================================

[Unit]
Description=Inventory Management System
Documentation=PLM Inventory Management Documents
After=network.target

[Service]
Environment=NODE_PORT=3000
Type=simple
User=superuser
WorkingDirectory=/home/superuser/inventory
ExecStart=/home/superuser/.npm-global/bin/nodemon --exec babel-node /home/superuser/inventory/server/server.js
Restart=on-failure

[Install]
WantedBy=multi-user.target

========================================

How can I deploy NextJS by systemd on ubuntu server?

Thanks in advance.


Solution

  • I am running it with the following unit file:

    [Unit]
    Description=NodeJS server, NextJS public frontend
    After=network.target
    
    [Service]
    Type=simple
    User=someuser
    Group=someuser
    Restart=on-failure
    RestartSec=10
    WorkingDirectory=/some/dir/
    ExecStartPre=/usr/bin/npm install
    ExecStartPre=/usr/bin/npm run build
    ExecStart=/usr/bin/npm run start
    
    [Install]
    WantedBy=multi-user.target
    
    

    The WorkingDirectory should point to the directory, where your NextJS project is.

    npm install installs the dependencies in node_modules. npm run build compiles some stuff, that ends up as static/ npm run start starts the NodeJS server.

    A lot of people suggest using pm2, but i am not a fan of it. If you are using CDI, you can get the npm run build and npm install into the build process, and then extract the artifacts (the file/folders mentioned below).

    Considering the way NextJS works, you should probably only need the following files and folders: node_modules/ static/ package.json package-lock.json next.config.js. Although, this too depends on your project.

    Of course, this is not nearly enough for production servers. Especially, since you will need to setup an webserver like Nginx or Apache, in order to do the location Proxy Pass to your NextJS application. This is because, the NextJS application is running under Localhost:PORT.