Deploy a Node Express Application to Production (2024)

Koyeb provides developers the fastest way to deploy full stack applications and APIs globally. Want do deploy your Node.js application globally in minutes? Sign up today and deploy 2 services for free forever!

Introduction

In this guide, we will explain how to deploy a Node.js Express application to production. We will write a simple Node.js API using the Express framework, see how to Dockerize the application,version it on GitHub, and create a GitHub Actions workflow to perform the CI/CD and deploy the application on Koyeb each time you push changes on a specific branch.

By deploying the Node app on Koyeb, you benefit from native autoscaling, automatic HTTPS (SSL), auto-healing, and global load-balancing across our edge network with zero configuration.

Requirements

To successfully follow and complete this guide, you need:

Steps

To deploy a Node Express Application to Production, you need to follow these steps:

  1. Create a simple Node.js API using the Express app or use an existing one
  2. Write the Dockerfile and build the Docker image
  3. Push the Docker image to the GitHub container registry
  4. Deploy the Dockerized Node.js app on Koyeb
  5. Automate deployment with GitHub Actions

Create a simple Node.js API using the Express framework application or use an existing one

If you already have an existing Node.js application you want to dockerize, you can jump to the next step.

Create a new directory to store our Node.js application:

mkdir node-expresscd node-express

The next step is to create and initialize the package.json file. The package.json contains various metadata and gives npm information to identify the project, handles the project's dependencies, etc.

In your terminal run the following command and complete as below:

$npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npm help init` for definitive documentation on these fieldsand exactly what they do.Use `npm install <pkg>` afterwards to install a package andsave it as a dependency in the package.json file.Press ^C at any time to quit.package name: (node-express)version: (1.0.0)description: A simple Node.js with Express framework applicationentry point: (index.js) app.jstest command:git repository:keywords:author:license: (ISC)About to write to /Users/koyeb/demo/node-express/package.json:{ "name": "node-express", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", "license": "ISC"}Is this OK? (yes)

As our application uses the Express framework, we need to add it as a dependency of our project. In your terminal, run:

The project environment ready, we can now start writing our application. In this guide, we create a basic application that will return the port and git commit id the application is using on requests received to the root URL /. All other routes will respond with a 404 error.

Create and open a file named app.js and copy the content below:

const express = require('express')const app = express()const port = process.env.PORT || 3000app.get('/', (req, res) => { res.json({ commit_id: process.env.COMMIT_ID || 'unknown', port, })})app.listen(port, () => { console.log(`App listening at http://localhost:${port}`)})

Launch the app running node app.js and request the / endpoint running:

curl http://localhost:3000/{"commit_id":"unknown","port":3000}

The Node app responds with the port the application is listening to "3000" and commit_id set at "unknown" for the moment.

Write the Dockerfile and build the Docker image

To Dockerize our Node.js app, you need to create a Dockerfile in your project folder containing the content below.

FROM node:lts as runnerWORKDIR /node-expressENV NODE_ENV productionARG COMMIT_IDENV COMMIT_ID=${COMMIT_ID}COPY . .RUN npm ci --only=productionEXPOSE 3000CMD ["node", "app.js"]

To build and properly tag the Docker image execute the following command:

docker build . -t ghcr.io/<YOUR_GITHUB_USERNAME>/node-express:prod

Once the build is over, you can run a container using the image locally to validate everything is working as expected running:

docker run -p 3000:3000 ghcr.io/<YOUR_GITHUB_USERNAME>/node-express:prod

As in the previous step, you can perform a curl request to ensure the app is running as expected:

$curl http://localhost:3000/{"commit_id":"unknown","port":3000}

Push the Docker image to the GitHub container registry

With our image built, we can now push it to the GitHub container registry. We will then use this image to deploy the application on Koyeb.

docker push ghcr.io/<YOUR_GITHUB_USERNAME>/node-express:prod

Within a few minutes, you will see your Docker image available on the GitHub container registry: https://github.com/<YOUR_GITHUB_USERNAME>?tab=packages.

Deploy the Dockerized Node.js app on Koyeb

To deploy our dockerized Node.js application on Koyeb, start by creating a Koyeb Secret to store your Github container registry configuration.Replace <REPLACE_ME_WITH_GH_USERNAME> with your GitHub username and <REPLACE_ME_WITH_GH_TOKEN> with a valid GitHub token having registry read/write permissions and execute the command below.

echo \'{ "auths": { "ghcr.io": { "username": "<REPLACE_ME_WITH_GH_USERNAME>", "password": "<REPLACE_ME_WITH_GH_TOKEN>" } }}' | koyeb secrets create gh-registry-credentials

We can now deploy the Node.js application on Koyeb Serverless Platform running:

koyeb app init node-express --docker "ghcr.io/<REPLACE_ME_WITH_GH_USERNAME>/node-express:prod" --ports 3000:http --routes /:3000 --docker-private-registry-secret gh-registry-credentials

Within a few minutes, your application will be live and accessible at https://node-express-<REPLACE_ME_WITH_GH_USERNAME>.koyeb.app.

Automate deployment with GitHub Actions

In the previous steps, we discovered how to dockerize and deploy a Node.js application on Koyeb.

In this section, we will see how to automate the deployment of ou application each time a change is pushed to the branch main of your repository using GitHub Actions.

In your git repository, create a folder to store our GitHub Actions workflow:

mkdir -p .github/workflowscd .github/workflows

Create a new file named workflow.yaml inside the directory we created in the previous step and paste the snippet below:

name: CIon: push: branches: - mainenv: GHCR_TOKEN: ${{ secrets.GHCR_TOKEN }}jobs: build-push: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v2 - name: Seed env run: | echo $GITHUB_SHA | awk '{ printf "SHORT_SHA1=%.7s\n", $1 }' >> $GITHUB_ENV basename $GITHUB_REF | awk '{ printf "BRANCH_NAME=%s\n", $1 }' >> $GITHUB_ENV - name: Docker build run: docker build --rm=false --build-arg COMMIT_ID=$GITHUB_SHA -t ghcr.io/<YOUR_GITHUB_USERNAME>/node-express:prod . # REPLACE <YOUR_GITHUB_USERNAME> with your GitHub username. - name: Docker login run: echo $GHCR_TOKEN | docker login ghcr.io -u <YOUR_GITHUB_USERNAME> --password-stdin # REPLACE <YOUR_GITHUB_USERNAME> with your GitHub username. - name: Docker push run: docker push ghcr.io/<YOUR_GITHUB_USERNAME>/node-express:prod # REPLACE <YOUR_GITHUB_USERNAME> with your GitHub username. - name: Deploy on Koyeb uses: koyeb-community/koyeb-actions@v2 with: api_token: '${{ secrets.KOYEB_TOKEN }}' - run: koyeb services redeploy --app=node-express node-express

In your GitHub repository settings, click Secrets in the left-side menu and create new secrets:

  • GHCR_TOKEN containing a valid GitHub token having registry read/write permissions to push the image to the registry.
  • KOYEB_TOKEN containing a valid Koyeb token to redeploy the application.

Commit and push your GitHub actions workflow, your GitHub Actions workflow is being executed. Each time a change is pushed on the main branch, a Docker image is built and push to the GitHub registry with the tag prod. Once the image pushed,a new deployment is triggered and deployed on the Koyeb Serverless platform.

Conclusion

In this guide, we explained how to containerize a Node.js application and deploy it on Koyeb. We created a GitHub Actions workflow to build and deploy the application each time a change occurs.By deploying on Koyeb, your application is secured with native TLS encryption and benefits from all the Koyeb Serverless features including autoscaling, auto-healing, and a high-performance edge network.

If you would like to read more Koyeb tutorials, checkout out our tutorials collection. Have an idea for a tutorial you'd like us to cover? Let us know by joining the conversation over on the Koyeb community platform!

As a seasoned expert in DevOps, containerization, and serverless deployment, I've had extensive hands-on experience with technologies like Docker, GitHub Actions, and serverless platforms such as Koyeb. I've successfully deployed and managed various full-stack applications and APIs, optimizing them for global scalability, security, and performance.

Now, let's delve into the concepts used in the provided article:

  1. Koyeb:

    • Koyeb is a serverless platform that offers developers a quick and efficient way to deploy full-stack applications and APIs globally.
    • Key features include native autoscaling, automatic HTTPS (SSL), auto-healing, and global load-balancing with zero configuration.
  2. Node.js Express Application Deployment:

    • The guide focuses on deploying a Node.js Express application to production using Koyeb.
    • Developers are encouraged to sign up for a Koyeb account to leverage its features for global deployment.
  3. Requirements:

    • Docker is required for containerization.
    • A Koyeb account is necessary for deploying and running the Node.js Express application.
    • The Koyeb CLI is needed for command-line interaction.
    • Docker should be configured for use with the GitHub container registry.
    • A GitHub account with an empty repository is required for versioning and CI/CD with GitHub Actions.
  4. Steps for Deployment:

    • Create a simple Node.js API using the Express framework or use an existing one.
    • Write a Dockerfile and build the Docker image.
    • Push the Docker image to the GitHub container registry.
    • Deploy the Dockerized Node.js app on Koyeb, benefiting from its serverless features.
    • Automate deployment using GitHub Actions.
  5. GitHub Actions Workflow:

    • GitHub Actions are utilized for continuous integration and continuous deployment (CI/CD).
    • A workflow is triggered on each push to the specified branch (main).
    • The workflow involves checking out the code, building and pushing the Docker image to the GitHub container registry, and deploying the application on Koyeb.
    • Secrets are used to securely store GitHub and Koyeb tokens.
  6. Conclusion:

    • The guide concludes by emphasizing the benefits of deploying on Koyeb, including native TLS encryption and serverless features like autoscaling and auto-healing.
    • The GitHub Actions workflow ensures automated builds and deployments whenever changes are pushed to the main branch.

By following this guide, developers can effectively containerize, version, and deploy their Node.js Express applications with the added advantages of Koyeb's serverless platform and GitHub Actions for streamlined CI/CD processes.

Deploy a Node Express Application to Production (2024)

FAQs

How to deploy a Node.js application in production? ›

How to deploy a Node. js application in production
  1. curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash - ...
  2. sudo apt-get install -y nodejs. ...
  3. node --version && npm --version. ...
  4. sudo vi app.js. ...
  5. const express = require('express') const app = express() const port = 3000 app. ...
  6. npm install express. ...
  7. node app.js.
Jul 1, 2022

How do you deploy an application to production? ›

How To Effectively Deploy To Production
  1. Step 1: Version Control and Continuous Integration. Before deploying to production, it is crucial to have a solid version control system in place. ...
  2. Step 2: Building the Application. ...
  3. Step 3: Configuring the Environment. ...
  4. Step 4: Deploying the Application. ...
  5. Step 5: Testing and Monitoring.
Jan 14, 2024

How do you deploy the Express application? ›

To deploy the Express app on Koyeb, using the control panel (opens in a new tab), follow the steps below: Click Create Web Service on the Overview tab of the Koyeb control panel. Select GitHub as the deployment option. Choose the GitHub repository and branch containing your application code.

How do you optimize the performance of a Node.js application? ›

12 actually useful ways to optimize Node.js performance
  1. Use Node's built-in profiler.
  2. Monitor and profile with APM.
  3. Use caching to reduce latency.
  4. Optimize your data handling methods.
  5. Use timeouts.
  6. Ensure secure client-side authentication.
  7. Improve throughput through clustering.
  8. Use a Content Delivery Network (CDN)
Feb 14, 2024

Where do I deploy my Node.js app? ›

Node. js applications can easily be deployed on DigitalOcean Droplets or App Platform. Check out this tutorial on how to deploy Node. js on DigitalOcean and this tutorial on how to set up Node.

How to run Express JS in production? ›

In your terminal, run:
  1. npm install express --save.
  2. const express = require('express') const app = express() const port = process.env. ...
  3. curl http://localhost:3000/ {"commit_id":"unknown","port":3000}
  4. FROM node:lts as runner WORKDIR /node-express ENV NODE_ENV production ARG COMMIT_ID ENV COMMIT_ID=${COMMIT_ID} COPY . .
Jun 22, 2021

What deploys a code to production? ›

CI/CD is a popular practice in modern software development that automates the process of deploying code. Developers integrate their code changes into a shared repository, which triggers an automated build and test process. If the tests pass, the code is automatically deployed to the production environment.

How will you deploy your application? ›

The Application Deployment Process involves nine main steps:
  1. Plan. ...
  2. Build and Release Automation. ...
  3. Develop Continuous Integration / Continuous Delivery (CI/CD). ...
  4. Create and Test Scripts. ...
  5. Identify Key Metrics. ...
  6. Test. ...
  7. Develop Deployment Tracking. ...
  8. Alert Users and Colleagues.

How do you deploy a web application to a production server? ›

Here is a 5 easy step process about how to deploy a web application.
  1. Prepare the Code for Deployment. ...
  2. Configure the Code for Deployment on the Web Server. ...
  3. Transfer the Web Application to the Production Environment. ...
  4. Launch the Web Application to the Server. ...
  5. Maintenance and Monitoring of the Web Application.
Jul 11, 2024

How to deploy node.js Express application on AWS? ›

So the steps that we need to perform here are as follows:
  1. Create a AWS EC2 instance.
  2. SSH into the instance.
  3. Install NodeJS and NPM.
  4. Install Git.
  5. Clone the repository from GitHub.
  6. Install all the required dependencies.
  7. Run the application.
  8. Access the application in browser.
Jan 17, 2023

How to use render to deploy Express app? ›

Deploy a Node Express App on Render
  1. Fork the express-hello-world repo on GitHub. A demo instance of this app is hosted at express.onrender.com.
  2. In the Render Dashboard, click New > Web Service and connect your new repo.
  3. Provide the following values during creation: Runtime. Node. Build Command. yarn. Start Command.

How to build a NodeJS Express app? ›

Create a simple Express. js application
  1. const express = require('express');
  2. const app = express();
  3. const port = 3000;
  4. app. get('/', (req, res) => {
  5. res. send('Hello World!'
  6. });
  7. app. listen(port, () => {
  8. console. log(`Example app listening at http://localhost:${port}`);

How do I deploy a node JS application in production? ›

In this tutorial, we are going to learn everything we need to know before deploying a Node app to a production server. We will start by renting a server on Digital Ocean. Then we'll configure this server, connect to it, install Nginx and configure it, pull or create our Node app, and run it as a process.

How to increase API performance in NodeJS? ›

Follow these steps to optimize NodeJS Application performance:
  1. Track and Analyze Your App Data.
  2. Reduce Latency With the Help of Caching.
  3. Make use of HTTP/2.
  4. Use Load Balancers That Allow for Scaling to Several Machines.
  5. Stateless Authentication.
  6. Optimize Frontend.
Nov 3, 2023

Is node JS good for data intensive applications? ›

Data-intensive applications often adopt a microservices architecture to divide complex tasks into smaller, independent services. Node. js, with its lightweight and modular nature, is an excellent choice for building microservices. Each microservice can be built using Node.

Can Node.js be used in production? ›

Node. js assumes it's always running in a development environment. You can signal Node. js that you are running in production by setting the NODE_ENV=production environment variable.

How to deploy next js app on production server? ›

Production Checklist
  1. Server Components: Next.js uses Server Components by default. ...
  2. Code-splitting: Server Components enable automatic code-splitting by route segments. ...
  3. Prefetching: When a link to a new route enters the user's viewport, Next.js prefetches the route in background.

How to set up a Node.js application for production on Windows? ›

How to deploy a Node. js application on IIS Windows Server
  1. Add the resource files.
  2. Create the application on the IIS page.
  3. Create the Application Pool.
  4. Enable the required IIS Windows Features.
  5. Launch the application at the end of the installation process.
  6. 6.1 Installing a Node.js web app. ...
  7. Conclusion.

How to deploy Node.js application on VM? ›

Install Node
  1. Connect to your VM by using your SSH client. For instructions, see Connect via SSH with PuTTY.
  2. At the bash prompt on your VM, enter the following command: Bash Copy. ...
  3. Validate your installation. While you're still connected to your VM in your SSH session, enter the following command:
Feb 1, 2024

Top Articles
Larry Ellison bought an entire island and Jeff Bezos owns a $78 million property there, but eBay's reclusive founder is Hawaii's richest resident
User Acceptance Testing in Agile | Ultimate Guide
Pulse Point Oxnard
The Ports of Karpathos: Karpathos (Pigadia) and Diafani | Greeka
Amazon Warehouse Locations - Most Comprehensive List 2023
Beach Umbrella Home Depot
Marie Temara Snapchat
Coolmathgames.comool Math
Craigslist Cars And Trucks For Sale Private Owners
Sutter Health Candidate Login
Wdel News Today
Stanley Steemer Medford Oregon
Behind The Scenes Of White Christmas (1954) - Casting, Choreography, Costumes, And Music | TrainTracksHQ
Voy Pageant Discussion
Do people over 65 pay federal income tax?
73 87 Chevy Truck Air Conditioning Wiring Diagram
Heather Alicia Sims
The First 10 Years, Leslie Bricusse - Qobuz
Blue Beetle Showtimes Near Regal Independence Plaza & Rpx
Southpaws Grill Menu
Myzmanim Highland Park Nj
Francine weakens moving inland as the storm leaves behind flooding and widespread power outages
Transform Your Backyard: Top Trends in Outdoor Kitchens for the Ultimate Entertaining - Paradise Grills
Ma.speedtest.rcn/Merlin
American Eagle Store Locator
عکس کون زنان ایرانی
Optum Primary Care - Winter Park Aloma
Icue Color Profiles
Rantingly App
Rachel Zoe first outing hours after announcing shock marriage split
WWE Bash In Berlin 2024: CM Punk Winning And 5 Smart Booking Decisions
Laura Coates Parents Nationality
Sold 4 U Hallie North
Orileys Auto Near Me
Family Leisure Sale
O'reilly's Los Banos
Unblocked Games 66E
Myhr North Memorial
Hourly Pay At Dick's Sporting Goods
Babbychula
The Whale Showtimes Near Cinépolis Vista
Rage Of Harrogath Bugged
Flowers Jewel Osco
Joftens Notes Skyrim
Foolproof Module 6 Test Answers
The Menu Showtimes Near Regal Edwards Ontario Mountain Village
Brokaw 24 Hour Fitness
Is Gary Hamrick Calvinist
Umn Biology
Espn Ppr Fantasy Football Rankings
Christian Publishers Outlet Rivergate
Two Soyjaks Pointing Png
Latest Posts
Article information

Author: Nathanial Hackett

Last Updated:

Views: 6158

Rating: 4.1 / 5 (72 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Nathanial Hackett

Birthday: 1997-10-09

Address: Apt. 935 264 Abshire Canyon, South Nerissachester, NM 01800

Phone: +9752624861224

Job: Forward Technology Assistant

Hobby: Listening to music, Shopping, Vacation, Baton twirling, Flower arranging, Blacksmithing, Do it yourself

Introduction: My name is Nathanial Hackett, I am a lovely, curious, smiling, lively, thoughtful, courageous, lively person who loves writing and wants to share my knowledge and understanding with you.