Steps to set JAVA enviroment variable on EC2 in 4 simple steps.
First, check the version of JDK
Step 1: Ensure you have right version of JAVA installed or upgrade if necessary (Optional)
The latest version of JAVA is 1.8, by default Amazon Linux has JAVA version 1.7 so you would directly want to upgrade it use below command :
sudo yum install java-1.8.0-openjdk.x86_64
If you already have JAVA installed you can change/check the JAVA version using below command.
$ sudo update-alternatives --config java
Select an option as shown in the image below:
Note: It is advisable to remove the previous version so that it doesn’t switch back.
Step 2: Find out where JAVA is!
For Linux systems, you can recursively run the command
file followed by
which command to find the JAVA installation location as shown in the image below.
$ file $(which java) /usr/bin/java: symbolic link to `/etc/alternatives/java'
The above output shows that java is pointing to a
/etc/alternatives/java file but that not the actual location of JAVA hence you will need to dig in more to fetch its actual path.
Step 3 : Follow the lead!
In the previous step, we located
/etc/alternatives/java file this file will get us to the actual location where JAVA config files are.
file command on that location
$ file /etc/alternatives/java /etc/alternatives/java: symbolic link to `/usr/lib/jvm/java-8-openjdk.x86_64/bin/java'
There you go… You’ve now located JAVA config file location which we will use in below steps to set JAVA environment variable
You can re-affirm the location running
file command on the symbolic path:
$ file /usr/lib/jvm/java-8-openjdk.x86_64/bin/java /usr/lib/jvm/java-8-openjdk.x86_64/bin/java: ELF 64-bit LSB executable...
This means that the JAVA is installed perfectly, Now go ahead and copy the path of above output
Step 4: Set JAVA environment variable
To set the JAVA_HOME environment variables on Linux/Unix go to
.bashrc file is different for each user in Linux, hence you will need to update the same file for every user you want to set environment variable for.
Copy paste below two lines in the
.bashrc file found in
home the directory of
export JAVA_HOME="/usr/lib/jvm/jdk-1.8.0-openjdk.x86_64" PATH=$JAVA_HOME/bin:$PATH
Save the file.
Alternatively, you can also set $PATH variable through the command line:
Run the following command to add $JAVA_HOME variable to
$ export PATH=$PATH:$JAVA_HOME/bin
That’s it! You’ve successfully set the environment variable for JAVA on EC2.
You check the JAVA and environment variable using this command :
$ echo $JAVA_HOME $ echo $PATH
This way you can then install a tomcat server without worrying about environment variable setting.
By default, AWS Linux AMI does not have environment variables set, so it’s recommended that you create an image of configuring AMI so that you don’t have to set variables every time you launch a new instance.
Hope this help!