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)
Top Articles
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.