In this article I will show you the steps for deploying a nodejs server which is on my local machine on a container which will act as a cloud machine (for ex. AWS EC2).
This can help you to understand how to setup an actual cloud deployment from the very basics.
These are the folllowing steps if you want to deploy a basic node application on a cloud service.
Prerequisite :
have linux
have docker installed
have node installed
Step 1 : Create a docker container using ubuntu:22.04 image
Start by pulling ubuntu:22.04 image and spinning up a container using this image :
sudo docker pull ubuntu:22.04
sudo docker run -it --name <server_name> ubuntu:22.04 /bin/bash
after running this command your terminal will turn into the container’s terminal and will look like this root@<container_id>:/
now update the container using this command :
apt update && apt upgrade -y
apt install sudo -y
Step 2 : Setting up SSH
In the Container :
First add a user admin
adduser admin usermod -aG sudo admin
switch to admin user
su - admin
Now lets setup SSH access
install openssh-server
sudo apt install -y openssh-server
start the service
sudo service ssh start
Now the SSH access has been setup and now we will generate a rsa key on the local machine and send that key to this container by its ip_address.
In the local machine :
Now open your local machine terminal and first get the ip_address of container :
docker inspect <container_name>
Generate an SSH key
ssh-keygen -t rsa
copy this to container
ssh-copy-id admin@<container_ip_address>
Now you can successfully SSH into your container from your local machine :
ssh admin@<container_ip_address>
Step 3 : Create simple nodejs server
In your local machine create an bun project
bun init
In the index.ts :
import express from "express";
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
res.status(200).json({
id: "1",
name: "John Doe",
});
});
app.listen(PORT, () => {
console.log(`Server Running on Port : ${PORT}`);
});
run the server using :
bun run index.ts
Step 4 : Deploying the server to bare metal container
copy your server files to the container
scp -r /path/to/your/app admin@<container_ip>:/home/admin/app
check in the SSH’d terminal if the files are present
ls /home/admin/app
install Node in the container :
sudo apt update
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
sudo apt install -y nodejs
check if node is installed
node --version
npm --version
install bun in the container
curl -fsSL https://bun.sh/install | bash
add bun to path
export BUN_INSTALL="$HOME/.bun"
export PATH="$BUN_INSTALL/bin:$PATH"
check if bun is installed
bun --version
run the server
bun run index.ts
Now on the browser go the domain http://<container_ip_address>:3000 you will see this :
{
"id": "1",
"name": "John Doe"
}
Server is successfully running on port 3000 in the container.