I am trying to install a suite of development tools on my Ubuntu server, but I keep getting errors stating that the JAVA_HOME environment variable is not defined. I have installed the OpenJDK, but I am unsure which configuration file I should edit—like .bashrc, .profile, or /etc/environment—to make sure the path persists after a system reboot. What is the standard procedure to locate the correct Java installation path and export it globally for all users?
3 answers
To set JAVA_HOME permanently for your user, you should first find your Java path by running readlink -f $(which java). Once you have the path (usually something like /usr/lib/jvm/java-17-openjdk-amd64), open your ~/.bashrc file with a text editor like nano. Add the following lines at the end of the file:
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$PATH:$JAVA_HOME/bin
After saving, run source ~/.bashrc to apply the changes immediately. This ensures that every time you open a new terminal session, your Java environment is correctly configured. For a system-wide setting that affects all users, you would follow similar steps but edit the /etc/environment file instead.
Does the update-alternatives --config java command provide a different path than the one found in the lib folder, and if so, which one is considered the "canonical" path for setting up environment variables in a production-grade Linux environment?
The easiest way is to add the export command to your /etc/profile file. This makes sure that no matter which shell you use—bash, zsh, or sh—the JAVA_HOME variable is always available.
I agree with Linda. Editing /etc/profile is the most robust method for servers where you might have multiple administrative users who all need access to the same Java runtime for various background services
That’s a great question, Daniel. The update-alternatives command is actually the preferred way to manage multiple Java versions. When setting JAVA_HOME, you should point it to the parent directory of the 'bin' folder shown in that list. If you use the symbolic link provided by alternatives, your JAVA_HOME will automatically update whenever you switch the default Java version using the alternatives system, which is much cleaner than hardcoding a specific version path.