Tuesday, January 28, 2014

Running Tomcat 7 on port 80 on Ubuntu 12.04.3

The goal:
  • Commission a new Amazon EC2 Instance running Ubuntu 12.04.3.
  • Install Apache Tomcat 7 and everything Tomcat requires to run.
  • Make Tomcat respond to requests on port 80.
How this differs from other tutorials you might have encountered:
  • It's for Ubuntu, not some other flavor of Linux where you can just set AUTHBIND=yes in an /etc/defaults/tomcat7 file.
  • It's for Tomcat 7, not some earlier version.
  • It doesn't just tell you to edit Tomcat's server.xml file, ignoring the fact that Ubuntu won't let a non-privileged user bind to ports below 1024.
  • It doesn't suggest running Tomcat as root, ignoring any resulting security concerns.
How to do it:
  • Create a new AWS EC2 Instance.
    • Select the AMI Ubuntu Server 12.04.3 LTS, 64-bit.
    • Use or create a security group that enables (at least) ports 22 and 80 for your IP address.
  • Use an SSH client to connect to the Instance. Most of the remaining steps will be performed in the SSH client.
  • Install Tomcat 7: 
    wget http://apache.mirrors.lucidnetworks.net/tomcat/tomcat-7/v7.0.50/bin/apache-tomcat-7.0.50.tar.gz
    tar -xzvf apache-tomcat-7.0.50.tar.gz
    rm apache-tomcat-7.0.50.tar.gz
    export CATALINA_HOME=/home/ubuntu/apache-tomcat-7.0.50
    export CATALINA_BASE=$CATALINA_HOME
  • Install JRE 7. Unfortunately, Oracle requires you to click to accept a license agreement, which you can't do from a headless server. So use another computer to visit http://www.oracle.com/technetwork/java/javase/downloads/server-jre7-downloads-1931105.html, download server-jre-7u51-linux-x64.tar.gz. Find a way to get this file to your home directory on the EC2 Instance. One possibility is to install an FTP or SFTP server on the Instance. Once the file is in your home directory:
cd ~ tar -xzvf /sftp/stevetest/incoming/server-jre-7u51-linux-x64.gz

export JAVA_HOME=/home/ubuntu/jdk1.7.0_51  
  • Use iptables to redirect requests on port 80 to port 8080
sudo iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080

sudo iptables -t nat -I OUTPUT -p tcp --dport 80 -j REDIRECT --to-ports 8080
  • Start Tomcat:
cd ~/apache-tomcat-7.0.50/bin ./startup.sh

  • Now if you type the EC2 Instance's IP address into your browser's address bar, you should see the Tomcat welcome page. No need to specify port 8080!
A tip of the hat goes to Tomcat: The Definitive Guide by Jason Brittain and Ian F. Darwin for a clear explanation of how to use iptables.

In future installments, I hope to cover setting up the server to automatically export the environment variables and start Tomcat when booted, and to enable SSL on port 443.

2 comments:

  1. Awesome dude!
    Worked like a charm and it was quick and easy just like I needed!
    Thanks a lot

    ReplyDelete
  2. Thanks so much. Have been working on this since morn

    ReplyDelete