What are the Instance types that can help me in installing the node on ec2?

237    Asked by Dadhijaraj in AWS , Asked on Jun 12, 2024

 I am a DevOps engineer for a particular tech-based company. My team is developing a new web-based application using the node.js and I need to set up a development environment on AWS. The application will initially run on a single EC2 Instance. My task is to prepare the EC2 Instance, ensuring node.js is installed and properly configured. How can I choose the appropriate Instance type for my development and what factors should I consider? 

Answered by Damini das

 In the context of AWS, here are the steps given for your given scenario:-

1. Provisioning the EC2 instance

Choosing the Instance type

First, try to select an instance type that should be based on the requirements of the resources and expected workload.

Security group Configuration

You should also Configure the security group to allow the inbound SSH traffic from your IP address or a specific range.

Installing the node.js

SSH into EC2 Instance

You can use the SSH -I ec2- user@ fir connecting to the EC2 instance.

Now you can install the node.js through Amazon Linux 2:-

Post-installation Configuration

Version compatibility

You should try to ensure that node.js meets the requirements of the application by checking compatibility with the framework and dependencies.

Environment setup

You can set up environment variables for creating project directories and configure any necessary tools or even libraries.

Here is the java based example given below:-

Import com.amazonaws.auth.AWSStaticCredentialsProvider;
Import com.amazonaws.auth.BasicAWSCredentials;
Import com.amazonaws.services.ec2.AmazonEC2;
Import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
Import com.amazonaws.services.ec2.model.*;Public class EC2NodeInstaller {
    Public static void main(String[] args) {
        // AWS credentials
        String accessKey = “YOUR_ACCESS_KEY”;
        String secretKey = “YOUR_SECRET_KEY”;
        // Initialize AWS credentials and EC2 client
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(Regions.US_EAST_1) // Specify your desired region
                .build();
        // Provision EC2 instance
        RunInstancesRequest runRequest = new RunInstancesRequest()
                .withImageId(“ami-xxxxxxxx”) // Specify your desired AMI
                .withInstanceType(InstanceType.T2Micro)
                .withMinCount(1)
                .withMaxCount(1)
                .withKeyName(“your-key-pair”)
                .withSecurityGroups(“your-security-group”);
        RunInstancesResult runInstancesResult = ec2Client.runInstances(runRequest);
        String instanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId();
        // Wait for instance to be running
        While (true) {
            DescribeInstancesRequest describeRequest = new DescribeInstancesRequest().withInstanceIds(instanceId);
            DescribeInstancesResult describeInstancesResult = ec2Client.describeInstances(describeRequest);
            InstanceState state = describeInstancesResult.getReservations().get(0).getInstances().get(0).getState();
            If (state.getName().equals(“running”)) {
                Break;
            }
            Try {
                Thread.sleep(5000); // Wait 5 seconds before checking again
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // SSH into the instance and install Node.js
        String sshCommand = “ssh -I your-key.pem ec2-user@instance-public-ip ‘sudo yum update -y && “ +
                “curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash - && “ +
                “sudo yum install -y nodejs’”;
        Try {
            Process process = Runtime.getRuntime().exec(sshCommand);
            Int exitCode = process.waitFor();
            If (exitCode == 0) {
                System.out.println(“Node.js installation successful.”);
            } else {
                System.out.println(“Node.js installation failed.”);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Additional configurations and setup can be done here
    }
}
Here is the Python based example given below:-
Import boto3
Import paramiko
Import time
# AWS credentials
Access_key = ‘YOUR_ACCESS_KEY’
Secret_key = ‘YOUR_SECRET_KEY’
Region = ‘us-east-1’ # Specify your desired region
# Initialize AWS session and EC2 client
Session = boto3.Session(
    Aws_access_key_id=access_key,
    Aws_secret_access_key=secret_key,
    Region_name=region
)
Ec2_client = session.client(‘ec2’)
# Provision EC2 instance
Response = ec2_client.run_instances(
    ImageId=’ami-xxxxxxxx’, # Specify your desired AMI
    InstanceType=’t2.micro’,
    MinCount=1,
    MaxCount=1,
    KeyName=’your-key-pair’,
    SecurityGroups=[‘your-security-group’]
)
Instance_id = response[‘Instances’][0][‘InstanceId’]
# Wait for instance to be running
While True:
    Describe_response = ec2_client.describe_instances(InstanceIds=[instance_id])
    State = describe_response[‘Reservations’][0][‘Instances’][0][‘State’][‘Name’]
    If state == ‘running’:
        Break
    Time.sleep(5) # Wait 5 seconds before checking again
# SSH into the instance and install Node.js
Instance_public_ip = describe_response[‘Reservations’][0][‘Instances’][0][‘PublicIpAddress’]
Key = paramiko.RSAKey.from_private_key_file(‘your-key.pem’) # Specify the path to your private key file
Ssh_client = paramiko.SSHClient()
Ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
Ssh_client.connect(hostname=instance_public_ip, username=’ec2-user’, pkey=key)
Commands = [
    ‘sudo yum update -y’,
    ‘curl -fsSL https://rpm.nodesource.com/setup_16.x | sudo bash -‘,
    ‘sudo yum install -y nodejs’
]
For command in commands:
    Stdin, stdout, stderr = ssh_client.exec_command(command)
    Exit_code = stdout.channel.recv_exit_status()
    If exit_code == 0:
        Print(f’Successfully executed command: {command}’)
    Else:
        Print(f’Error executing command: {command}’)
Ssh_client.close()
# Additional configurations and setup can be done here


Your Answer

Interviews

Parent Categories