Skip to content

How to install Java on your EC2 instance in 2025?

Published:ย atย 01:16 PM

Last weekend, I was setting up JMeter for load testing. Instead of stressing my local machine ๐Ÿ’ป, I decided to spin up an Ubuntu-based EC2 instance on AWS. But before installing JMeter, I needed Java on the instance.

If youโ€™re setting up Java on an AWS EC2 instance, this guide is for you. Letโ€™s get started!


๐Ÿš€ Step 1: Launch an EC2 Instance

  1. Login to your AWS Console and navigate to the EC2 Dashboard.
  2. Click Launch Instance and configure the instance as per your requirements.
  3. Make sure to download the .pem key file during the final stepsโ€”this is needed for SSH access.
  4. For this guide, weโ€™re using an Ubuntu-based EC2 instance.

Java on EC2

๐Ÿ›  Step 2: Connect to Your EC2 Instance

Once your instance is up and running, connect via SSH from your local terminal.

  1. Move to the directory where your .pem file is stored and update its permissions:

    chmod 400 mypemfile.pem
  2. Connect to the EC2 instance:

    ssh -i "mypemfile.pem" ubuntu@ec2-x-xxx-xx-0.ap-south-1.compute.amazonaws.com

โœ… Pro Tip: Ensure youโ€™re in the same directory as your .pem file before running the SSH command.


๐Ÿ“Œ Step 3: Install Java on EC2

  1. Switch to a superuser:

    sudo -i
  2. Update the package list to ensure everything is up to date:

    sudo apt update && sudo apt upgrade -y
    
  3. Verify if Java is already installed (most likely, itโ€™s not):

    java -version

๐Ÿ“‚ Step 4: Create a Directory for Java

  1. Navigate to the /usr/lib/ directory:

    cd /usr/lib/
  2. Create a new jvm directory:

    mkdir jvm
  3. Grant proper permissions:

    chmod u=rwx,g=rwx,o=rwx jvm

๐Ÿ”„ Step 5: Upload Java JDK to Your EC2 Instance

  1. Exit from your EC2 session (exit) and upload the JDK file from your local machine:

    scp -i "mypemfile.pem" ~/Downloads/jdk-11.0.25_linux-x64_bin.tar.gz ubuntu@ec2-x-xxx-xx-0.ap-south-1.compute.amazonaws.com:/usr/lib/jvm
  2. Once the upload is complete, reconnect to your EC2 instance and navigate to the jvm directory:

    cd /usr/lib/jvm
  3. Extract the JDK archive:

    tar zxvf jdk-11.0.25_linux-x64_bin.tar.gz

๐ŸŒŽ Step 6: Set Up Java Environment Variables

  1. Open the environment file for editing:

    nano /etc/environment
  2. Add the following lines to the file:

    PATH="/usr/lib/jvm/jdk-11.0.25/bin:$PATH"
    JAVA_HOME="/usr/lib/jvm/jdk-11.0.25"
  3. Save and exit (CTRL + X, then Y, then Enter).


๐Ÿ›  Step 7: Configure Java Alternatives

Run the following commands to let the system recognize Java and javac:

update-alternatives --install "/usr/bin/java" "java" "/usr/lib/jvm/jdk-11.0.25/bin/java" 0
update-alternatives --install "/usr/bin/javac" "javac" "/usr/lib/jvm/jdk-11.0.25/bin/javac" 0

โœ… Step 8: Verify Java Installation

Run:

java -version

Java version

๐ŸŽ‰ Boom! Java is now installed on your AWS EC2 instance! ๐Ÿš€๐Ÿ”ฅ