Deploying a Bun Application to EC2 with Nginx

Deploying a Bun Application to EC2 with Nginx
Bun
PM2
EC2

Junius L

September 17, 2023

2 min read

Deploying a Bun Application to EC2 with Nginx

In this tutorial, we will guide you through the process of deploying a Bun application to an Amazon EC2 instance and configuring Nginx as a reverse proxy to efficiently serve your application. This setup allows you to host your Bun application securely and reliably.

Prerequisites

Before we begin, ensure you have the following prerequisites in place:

  1. An AWS account with an active EC2 instance.
  2. Your Bun application code ready for deployment.
  3. SSH access to your EC2 instance.

Step 1: Set Up Your EC2 Instance

  1. Launch an EC2 instance on AWS. Choose an appropriate Amazon Machine Image (AMI), instance type, and configure the security group to allow incoming traffic on necessary ports (e.g., HTTP port 80 and SSH port 22).

    User data

    #!/bin/bash
     
    yum update -y && yum install git nginx -y && systemctl enable --now nginx

Once your EC2 instance is running, connect to it using SSH:

ssh -i YourKey.pem ec2-user@YourEC2PublicIP

Install NVM and Node.js

PM2 requires Node.js

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
nvm install node

Install Bun

curl -fsSL https://bun.sh/install | bash

Clone the Repository from GitHub

git clone https://github.com/julekgwa/Elysia-with-Bun-runtime.git

Install Dependencies

cd Elysia-with-Bun-runtime
bun install

Install PM2 Globally

bun add -g pm2

Start the Application

pm2 start bun --name bun-prod -- dev

Add Nginx Proxy

Open /etc/nginx/nginx.conf:

sudo vi /etc/nginx/nginx.conf

And paste the following code:

server {
    listen 80;
    server_name _;
 
    location / {
        proxy_pass  http://localhost:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

Source code

https://github.com/julekgwa/Elysia-with-Bun-runtime

Conclusion

In this tutorial, we have successfully deployed a Bun application to an Amazon EC2 instance and configured Nginx as a reverse proxy to efficiently serve the application. This setup ensures your Bun application is hosted securely and is ready for production use. You can further customize and scale this environment to meet your specific requirements.

Happy deploying!