tomcat 权威指南资料


Tomcat The Definitive Guide SECOND EDITION Jason Brittain with Ian F. Darwin Beijing • Cambridge • Farnham • Köln • Paris • Sebastopol • Taipei • Tokyo Tomcat: The Definitive Guide, Second Edition by Jason Brittain with Ian F. Darwin Copyright © 2008 O’Reilly Media, Inc. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com. Editor: Simon St.Laurent Production Editor: Loranah Dimant Copyeditor: Nancy Reinhardt Proofreader: Loranah Dimant Indexer: Tolman Creek Design Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Jessamyn Read Printing History: June 2003: First Edition. October 2007: Second Edition. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Tomcat: The Definitive Guide, the image of a snow leopard, and related trade dress are trademarks of O’Reilly Media, Inc. Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun Microsystems, Inc., in the United States and other countries. O’Reilly Media, Inc. is independent of Sun Microsystems. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a trademark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. This book uses RepKover™, a durable and flexible lay-flat binding. ISBN-10: 0-596-10106-6 ISBN-13: 978-0596-10106-0 [M] v Table of Contents Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix 1. Getting Started with Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Installing Tomcat 1 Starting, Stopping, and Restarting Tomcat 17 Automatic Startup 29 Testing Your Tomcat Installation 34 Where Did Tomcat Come From? 35 2. Configuring Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 A Word About Using the Apache Web Server 38 Relocating the Web Applications Directory 39 Changing the Port Number from 8080 42 Java VM Configuration 51 Changing the JSP Compiler 54 Managing Realms, Roles, and Users 55 Controlling Sessions 70 Accessing JNDI and JDBC Resources 75 Servlet Auto-Reloading 78 Customized User Directories 78 Tomcat Example Applications 80 Common Gateway Interface (CGI) 80 The Tomcat Admin Webapp 82 vi | Table of Contents 3. Deploying Servlet and JSP Web Applications in Tomcat . . . . . . . . . . . . . . . . . 86 Layout of a Web Application 93 Deploying an Unpacked Webapp Directory 95 Deploying a WAR File 100 Hot Deployment 106 Working with WAR Files 107 The Manager Webapp 108 Automation with Apache Ant 111 Symbolic Links 124 4. Tomcat Performance Tuning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126 Measuring Web Server Performance 127 External Tuning 153 Internal Tuning 156 Capacity Planning 164 Additional Resources 167 5. Integration with the Apache Web Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 The Pros and Cons of Integration 170 Installing Apache httpd 174 Apache Integration with Tomcat 177 Tomcat Serving HTTP over the APR Connector 194 6. Tomcat Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201 Securing the System 202 Multiple Server Security Models 204 Using the SecurityManager 205 Granting File Permissions 208 Setting Up a Tomcat chroot Jail 213 Filtering Bad User Input 224 Securing Tomcat with SSL 241 7. Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259 server.xml 260 web.xml 316 tomcat-users.xml 333 catalina.policy 333 catalina.properties 334 context.xml 335 Table of Contents | vii 8. Debugging and Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336 Reading Logfiles 336 Hunting for Errors 337 URLs and the HTTP Conversation 337 Debugging with RequestDumperValve 342 When Tomcat Won’t Shut Down 343 9. Building Tomcat from Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 Installing Apache Ant 348 Obtaining the Source 349 Downloading Support Libraries 351 Building Tomcat 352 10. Tomcat Clustering . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354 Clustering Terms 355 The Communication Sequence of an HTTP Request 356 Distributed Java Servlet Containers 366 Tomcat 6 Clustering Implementation 370 JDBC Request Distribution and Failover 388 Additional Resources 389 11. Final Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 391 Supplemental Resources 391 Community 395 A. Installing Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397 B. jbchroot.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410 C. BadInputValve.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416 D. BadInputFilter.java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426 E. RPM Package Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439 Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463 This book is lovingly dedicated to our son Alex and our daughter Angie. —Jason Brittain ix Preface1 Tomcat has eased the lives of thousands of Java™ developers, supplying them with a free environment for testing anddeployingweb applications. Tomcat has provedits mettle in all kinds of environments, providing the foundation you’ll need to apply your Java expertise to the Web. What’s This Book About? Tomcat is a Java servlet container andweb server from the Apache Software Founda- tion (http://tomcat.apache.org). A web server is, of course, a program that dishes out web pages in response to requests from, for example, a user sitting at a web browser. But web servers aren’t limitedto serving up static HTML pages; they can also run programs in response to user requests andreturn the dynamicresults to the user’s browser. This is an aspect of the Web that Apache’s Tomcat is very goodat because Tomcat provides both Java servlet and JavaServer Pages (JSPs) technologies (in addi- tion to serving traditional static pages and external CGI programs written in any pro- gramming language). The result is that Tomcat is a goodchoice for use as a web server for many applications, including using it as a high performance production web server. Andit’s a very goodchoice if you want a free, open source ( http:// opensource.org) servlet andJSP engine. It can be usedstandaloneandin conjunction with other web servers such as Apache httpd. This book is about how to use Tomcat itself. If you’re looking for detailed informa- tion andtutorials about how to write web applications, be sure to read Java Servlet Programming by Jason Hunter with William Crawford (O’Reilly). x | Preface Why an Entire Book on Tomcat? Can’t you just download and run Tomcat from the Apache Software Foundation’s web site? Well, of course you can, andyou’ll needto, but there is a lot more to Tom- cat than just getting it running. You’ll get more out of Tomcat if you understand how andwhy it was written. So in Chapter 1, Getting Started with Tomcat, we explain that. You will then be better able to make informeddecisionson choices you might needto make when installing Tomcat, so we spendthe rest of the chapter on the installation and startup procedures. In Chapter 2, Configuring Tomcat, we show you all about configuring Tomcat. We talk about when you shoulduse Tomcat as a standaloneweb server andservlet container andwhen it’s best to use Tomcat with the Apache httpd web server. Then, we show you how to configure realms, roles, users, servlet sessions, andJNDI resources, includ- ing JDBC DataSources. Next, we show how to turn on andoff the auto-reloadingof servlets, how to relocate the webapps directory, and how to map user home directories for access through Tomcat. Then, we go over how to enable anddisablethe example web applications andhow to enable common gateway interface scripting in Tomcat. And finally, we close out the chapter by introducing you to the Tomcat administration web application, which allows you to configure Tomcat through your web browser. With Tomcat installedandconfiguredjust the way you like it, you’re readyto learn more about servlet andJSP web applications andhow to deploythem into your Tomcat. In Chapter 3, Deploying Servlet and JSP Web Applications in Tomcat,we show you the layout of a web application, how to deploy a web application, and how to deploy individual servlets and JSP pages. Next, we show you how to build web application archive files and how to deploy them. To make things less tedious, we review how to automate the deployments of your web applications by copying, using the built-in manager web application, and using the Jakarta Ant build tool. Once you have Tomcat serving your web application, you may want to do some per- formance tuning. In Chapter 4, Tomcat Performance Tuning, we show you how to measure andimprove your Tomcat’s performance. We go over adjustingthe num- ber of processor Threads, JVM andOS performance issues as they relate to Tomcat, turning off DNS lookups, andhow to speedup JSPs. We roundout the chapter by discussing how capacity planning can affect performance. Tomcat works as a complete standalone web server. It supports static web pages, external CGI scripts, andmany of the other paraphernalia associatedwith a web site. However, Tomcat’s forte, its raison d’etre, is to be the best servlet andJSP engine on the block. These are the things it does best. If you already run Apache’s httpd web server anddon’twant to change everything all at once, Chapter 5, Integration with the Apache Web Server, covers the use of Tomcat with Apache httpd andtalks about the several ways of making Tomcat thrive “in front of” or “behind” an Apache httpd installation. Preface | xi Whether you’re providing e-commerce, putting up a mailing list, or running a per- sonal site, when you’re connectedto the Internet, your site is exposedto a lot of peo- ple, including a few weirdos who think it’s OK to exploit the vulnerabilities in your server software for fun and/or profit. Because security is important, we devote Chapter 6, Tomcat Security, to the topic of how to keep the online thugs at bay. In Chapter 7, Configuration, we talk about the Tomcat configuration files, server.xml and web.xml, as well as tomcat-users.xml, catalina.policy, catalina.properties, and con- text.xml files. Each can be modified to control how Tomcat works. When something goes wrong with your Tomcat or a web application, Chapter 8, Debugging and Troubleshooting, shows you some ways to diagnose the problem. We show you what to look for in the logfiles, how the web browser interacts with Tom- cat’s web server during a request, how to get verbose information about a particular request, and what to do if Tomcat just won’t shut down when you tell it to. Not everyone wants to run a prebuilt binary release of Tomcat, so in Chapter 9, Building Tomcat from Source, we show you how to compile your own Tomcat. We show you step-by-step how to install the Apache Ant buildtool, downloadallneces- sary support libraries, and build your Tomcat. If you’ve got more request traffic than a single Tomcat can handle, or if you want your site to keep serving requests even if one of your servers crashes, your site may needto run on more than one Tomcat server, or more than one Apache, or a combi- nation of the two. Sometimes the only solution is more hardware. In Chapter 10, Tomcat Clustering, we show you some options for running two or more Tomcat serv- let containers in parallel for both fault tolerance andhigher scalability, andwe dis- cuss the pros and cons of various clustering approaches. In Chapter 11, Final Words, we give an overview of the Tomcat open source project’s community resources, including docs, mailing lists, other web sites, and more. These are valuable resources for solving any problems you may have with future versions of Tomcat, andthey can also help you get more involvedin the developmentof Tom- cat if that is one of your goals. Depending on your operating system, installing Java may not be as straightforward as you think. To ensure that Tomcat runs well on your server computer, in Appendix A, Installing Java, we show you step-by-step how to install a Java runtime, andexplain some Java issues to watch out for. xii | Preface Who This Book Is For The book is written for anyone who wants to learn about the Tomcat servlet con- tainer. You do not have to be a programmer to use Tomcat or this book; all of the Java programming is, as mentionedabove, tuckedaway insideservlets or other com- ponents. You may be a system or network administrator who wants to run a small simple web site. You may be an experiencedApache Web Server webmaster who needs to run one or more servlets or JSPs as part of a larger site, or a programmer who is developing Java web components and wants to get up to speed quickly on using Tomcat as a web application server during development and in production. Maybe you’re running one of the many Java EE servers that include Tomcat as their web container. For any of these reasons andfor any other readers,this book pro- vides an excellent introduction to Tomcat. Conventions Used in This Book The following typographic devices are used: Italic Used for filenames, URLs, Java classes, and for new terms when they are defined. Constant width Used for code examples, XML elements, and commands. constant width bold Indicates user input or lines of particular note in code examples. constant width italic Indicates text that should be replaced with user-supplied values. Indicates a tip, suggestion, or general note. Indicates a warning or caution. Additionally, the initials SRV with a dotted-decimal number after them refers to the indicated section in the Servlet Specification, Version 2.5. For example, SRV.6.5 refers to Section 6, subsection 5 of the Servlet Specification. Similarly, JSP with a dot- tednumber refers to the given section in the JSP specification. You can downloadthe servlet andJSP specifications from http://java.sun.com/products/servlet and http:// java.sun.com/products/jsp, respectively. Preface | xiii Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book andquoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, andISBN. For example: “ Tomcat: The Definitive Guide, SecondEdi- tion, by Jason Brittain with Ian F. Darwin. Copyright 2008 O’Reilly Media, Inc., 978-0- 596-10106-0.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. We’d Like to Hear from You Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any addi- tional information. You can access this page at: http://www.oreilly.com/catalog/9780596101060 To comment or ask technical questions about this book, send email to: bookquestions@oreilly.com For more information about our books, conferences, Resource Centers, andthe O’Reilly Network, see our web site at: http://www.oreilly.com There are also web sites for this book by its authors: http://tomcatbook.darwinsys.com http://tomcatbook.brittainweb.org xiv | Preface Safari® Books Online When you see a Safari® Books Online icon on the cover of your favorite technology book, that means the book is available online through the O’Reilly Network Safari Bookshelf. Safari offers a solution that’s better than e-books. It’s a virtual library that lets you easily search thousands of top tech books, cut and paste code samples, download chapters, andfindquick answers when you needthe most accurate, current informa- tion. Try it for free at http://safari.oreilly.com. Acknowledgments Thanks to James Duncan Davidson and Sun Microsystems for giving us Tomcat in the first place. James workedabove andbeyondthe call of dutyto write it andto work out the details of how it could become open source software. Sun Microsystems supportedhis pioneering work andhas strongly supportedthe evolu- tion of Tomcat since its donation to the Apache Software Foundation. A colossal thanks goes to Simon St.Laurent, editor of this Second Edition after Brett McLaughlin, for being patient with me beyondmy expectations while I spent the necessary time digging deep to uncover and clearly document the answers through- out the book, and for showing continued confidence. Another big thanks goes to Brett McLaughlin, who edited the First Edition and was the editor of this Second Edition in the early months of the project. Brett made innu- merable minor suggestions to improve the book andseveral times talkedus into reor- ganizing scatteredmaterial into the (hopefully) comprehensible form you see before you. Thanks Brett! Paula Ferguson saw the First Edition of the book through the early stages, and then passed the torch to Brett McLaughlin. Thanks Paula! Open source projects are just not the same without a vibrant community surround- ing them, andwe believe that Tomcat couldnot have gone so far so fast without the stewardship of the Apache Software Foundation and its members. Thanks, ASF, for your hard work, servers, and bandwidth. Jason Hunter, author of O’Reilly’s Java Servlet Programming, provided a very care- ful reading of the drafts of the First Edition, and suggested many, many improve- ments. Special thanks to you, Jason. Preface | xv Jason Brittain’s Acknowledgments A big thanks to my wife Carmina, for taking care of the little ones while I wrote, over the course of more than two years. Thanks, Cutie, for all the help you gave me while I wrote this edition of the book, and for being inspirational to me, and now to our children. I love you very much, and I always will! Thanks to James Duncan Davidson and Jason Hunter who together had a strong vision of excellence for the First Edition of this book and worked hard to make that vision a reality. I’dlike to personally thank Simon St.Laurent for the help andsupport for this book. The level of detail and clarity demonstrates how much Simon worked to make sure I had the time to write it that way. Thanks Simon! Thanks also go to Ian Darwin for coauthoring the first edition of the book. He wrote a large amount of helpful andvirtually timeless Tomcat content that remains in this Second Edition. The person who directly contributed the most content for the Second Edition of this book (besides Simon St.Laurent, the editor through most of the project), was Akbar Ansari. He provided many screen shots that would have taken me countless addi- tional hours to create, he graphedbenchmark datanumerous times, proofreadsome of my text andgave me feedback,andmost importantly gave me wordsof encour- agement as I wrote. Thanks, Akbar, for being so helpful and genuinely interested! Thanks also to Jamie Madden for being the tech reviewer for the Second Edition. Bart Busschots and Jamie Madden both wrote the Mac OS X specific sections of this book—excellent pioneering work guys! Thanks! Also Sebastien Diotte implementedthe initial 5.5+ port of BadInputValve, Sean McCauliff gave feedback about textual strangeness in some chapters, and Mike Miller showedme an important FreeBSD ipfilter port remapping rule. Thanks to Mark Petrovic for conversing with me about the SecurityManager andfor writing the security policy autodiscovery article; Nicholas Schuetz for creating and maintaining the #tomcat IRC channel on the irc.freenode.net server (it has helpedcountless Tom- cat users); Philip Morton, Robert Brindamour, and Tom Duggin for fixing a scalabil- ity bug in BadInputValve; William Osmond(I forgot to write in my notes what you helpedwith, but I know you helped!Thanks!); Fabrice Bellardandothers for writ- ing QEMU so that I couldrun so many differentoperating systems to write about them; and Jason Gabler for showing me sventon. Thanks to my former co-workers andfriendsat NASA’s Ames research center, and the NASA Kepler Space Telescope mission (http://kepler.nasa.gov) for allowing me to participate. Eventually, our software will findmany new habitable worlds,never before detected by mankind. xvi | Preface I want to also thank Rodney Joffe formerly of Genuity for having lots of confidence in me early on in my career, andfor introducingme to the subjects of high availabil- ity, loadbalancing, andfault tolerance back in 1996. Also, to DavidJemmett, for- merly of GoodNet, for not only giving me my first big break as a software engineer and system administrator, but also for giving me a starting point into dynamic web content development in mid-1995. I’m grateful to each of you! I also wish to acknowledge and thank Theron Tison, who is the most thoughtful, unselfish, caring person I hadthe pleasure of being aroundwhile growing up. He was the pillar of stability andconfidencethat allowedme to reach virtually all of my goals. Thank you, Theron, for helping me through so many tough years. Ian Darwin’s Acknowledgments Mike Loukides encouraged me to find an O’Reilly book to write, when a competing publisher tried to lure me away after the success of Java Cookbook. Kevin Bedell read the manuscript carefully cover to cover and suggested many improvements (as well as spotting several errors and omissions). Thanks, Kevin. I have, over the years, learneda lot about JavaServer Pages from ChadDarby, author of Learning Tree’s (http://www.learningtree.com) course on servlets andJavaServer Pages. Chad also did a helpful review of the manuscript. And, of course, to Betty, the woman of my life, and our children Benjamin, Andy, and Margaret. Thanks for your support and for the time away. My special warm thanks to Jason for taking over anddoingall of the revisions for this SecondEdition,when I foundI hadother fish to fry. An extra big “+1” to you, Jason, for sticking with it to completion despite the needs of your growing family! 1 Chapter 1 CHAPTER 1 Getting Started with Tomcat1 Because Tomcat is written in Java, some people assume that you have to be a Java guru to use it. That is not so! Although you needto know Java to modifythe inter- nals of Tomcat or to write your own servlet programs, you do not need to know any Java to use Tomcat or to write or maintain many JavaServer Pages (JSPs). You can have JSPs that use “JavaBeans” or “JSP Custom Tags”; in both cases, you are simply using Java components that a developer has set up for you. In this chapter, we explain how to install Tomcat, get it running, andtest it to make sure that it’s functioning properly. As of this writing, there are several production-ready versions of Tom- cat available, but we strongly suggest you use the latest stable version of the 6.0 branch or whichever is the latest stable version of Tomcat by the time you readthis. See the Apache Tomcat home page ( http://tomcat. apache.org) to findthe latest stable version. For Tomcat versions 5.5 and 6.0, this book provides an abundance of answers and explanations about the general concepts of how Tomcat works, in addition to show- ing rich detail about how to use these popular versions of Tomcat. Installing Tomcat There are several paths to getting Tomcat up andrunning. The quickest one is to downloadandrunthe compiledbinary. Tomcat is written in Java, which means you needto have a modernandcomplete Java runtime installedbefore you can buildor test it. ReadAppendixA to make sure you have Java installedproperly. Do not skip this step; it is more important than it sounds! One of the benefits of open source projects is that programmers findandfix bugs andmake improvements to the software. If you’re not a programmer, there is little or nothing to be gainedfrom recompiling Tomcat from its source code,as you are not interestedin this level of interaction. Also, if you’re not an experiencedTomcat 2 | Chapter 1: Getting Started with Tomcat developer, attempting to build and use your own Tomcat binaries may actually cause problems because it is relatively easy to buildTomcat in ways that quietly disable important features. To get startedquickly, you shoulddownloadanofficial release binary package for your system. If you want some hints on compiling from source, see Chapter 9. There are two levels of packaging. The Apache Software Foundation publishes bina- ries in the form of releases and nightly builds. Other organizations rebundle these into RPM packages andother kindsof installers for Linux, “packages” for BSD, and so forth. The best way to install Tomcat depends on your system. We explain the process on several systems: Linux, Solaris, Windows, Mac OS X, and FreeBSD. Tomcat 6 requires any Java runtime version 1.5 or higher (which Sun’s marketing group calls “Java 5”). We suggest that you run Tomcat 6 on Java 1.6 or higher, how- ever, due to the additional features, fixes, and performance improvements that Java 1.6 (or higher) JVMs offer. Installing Tomcat on Linux Tomcat is available in at least two different binary release forms for Linux users to choose from: Multiplatform binary releases You can download, install, and run any of the binary releases of Tomcat from Apache’s web site regardless of the Linux distribution you run. This format comes in the form of gzippedtar archives ( tar.gz files) andzip archive files. This allows you to install Tomcat into any directory you choose, and you can install it as any user ID in the system. However, this kindof installation is not trackedby any package manager and will be more difficult to upgrade or uninstall later. Also, it does not come with an init script for integration into the system’s star- tup and shutdown. Distribution native package If you run Fedora or Red Hat Linux (or another Linux that uses the Red Hat package manager, such as SUSE or Mandriva), you can download a binary RPM package of Tomcat. This allows for easy uninstalls andupgradesvia the RedHat Package Manager, plus it installs a Tomcat init script for stopping, starting, and restarting Tomcat from the command line and on reboots. The downside to this methodof installation is that you must install the Tomcat RPM package as the root user. As of this writing there are at least two RPM package implementa- tions for you to choose from, each with different features. Installing Tomcat | 3 Keep in mind, though, that Linux is just the operating system kernel, and the com- plete operating system is a “distribution.” Today, there are many different Linux dis- tributions. Some examples include Fedora, Red Hat, Ubuntu, Mandriva, Gentoo, andDebian. Although any two Linux distributionstendto be similar, there are also usually enough differences that make it difficult for developers to write one script that runs successfully on two. Also, each Linux distribution may primarily use a dif- ferent native package manager, so each version of a distribution can change any number of things in the operating system, including Java* andTomcat. It is not uncommon for Linux distributions to bundle software written in Java that does not work only because the distribution’s own package of it is broken in a subtle way. Distributions also tendto includeoldversions of Tomcat that are either unstable or less than ideal to run your web site compared to the latest stable version available. For these reasons, it’s almost always best to install your own recent stable version of Tomcat. Because there are so many Linux distributions, and because they are significantly dif- ferent from each other, giving specific instructions on how best to install Tomcat on each version of each Linux distribution is beyond the scope of this book. Luckily, there is enough similarity between the popular Linux distributions for you to follow more generic Linux installation instructions for installing Tomcat from an Apache binary release archive. If you run a Fedora or Red Hat Linux distribution, more than one implementation of Tomcat RPM packages exists for you to choose from: The Tomcat RPM package that comes with this book This is a fully relocateable RPM package that can be easily rebuilt via a custom ant build file. It does not build Tomcat itself but instead bundles the official mul- tiplatform Apache release class binaries of the Tomcat 6 version of your choice. This RPM package depends on no other RPM packages, so it can be installed as a single package, but needs to be configured to use an installed Java runtime (JDK or JRE). See Appendix E for the full source listing of the RPM package’s scripts. The Tomcat RPM package that is available from JPackage.org This is a nonrelocateable RPM package that installs Tomcat into the /var direc- tory. It rebuilds Tomcat from source code and then packages up the resulting multiplatform class binaries. This RPM package depends on many other RPM packages (each potentially requiring yet more packages) from JPackage.org and must be installedas a graph of RPM packages. As of this writing, JPackage.org does not have a Tomcat 6.0 RPM, only a Tomcat 5.5 RPM. * See Appendix A for more information about how to work around a distribution’s incompatible Java implementation. 4 | Chapter 1: Getting Started with Tomcat Each of these RPM packages includes detailed scripts for installing, uninstalling, and upgrading Tomcat, as well as scripts for runtime integration with the operating sys- tem. We suggest you try ours first. If you run Gentoo Linux, there is an ebuildof Tomcat 6 that you can install anduse. See the guide for it by William L. Thomson Jr. at http://www.gentoo.org/proj/en/java/ tomcat6-guide.xml. Also, see the Tomcat Gentoo ebuildpage on the Gentoo Wiki at http://gentoo-wiki.com/Tomcat_Gentoo_ebuild. In addition to the ebuild, the RPM package from this book is written to install andrun on Gentoo; just install the rpm command first. Installing Tomcat from an Apache multiplatform binary release For security reasons, you shouldprobably create a tomcat user with low privileges andrun Tomcat as that user. We suggest setting that user’s login shell to /sbin/ nologin andlocking the user’s passwordso that it can’t be guessed.Also, it’s proba- bly a goodideato make the tomcat user’s primary group the nobody group or another group with similarly low permissions. You will need to do this as the root user: # useradd -g 46 -s /sbin/nologin -d /opt/tomcat/temp tomcat If you do not have root access, you could run Tomcat as your login user, but beware that any security vulnerabilities (which are extremely rare) in Tomcat couldbe exploited remotely as your user account. Now download a release archive from the Apache binary release page at http:// tomcat.apache.org/download-60.cgi. You shoulddownloadthelatest stable version as listed on the Tomcat home page at http://tomcat.apache.org. Even if you intendto install only a subset of the archive files of the Tomcat version you chose, you shoulddownload all of the archive files for that version in case you needthem later. The Apache Soft- ware Foundation does archive releases of Tomcat, but you should store your own copies as well. If you are a heavy user of Tomcat, you should probably also download archives of the source code for your release andstore your own copies of them as well so that you may investigate any potential bugs you may encounter in the version you’ve chosen. Uncompress the main Tomcat binary release archive. If you downloaded the apache- tomcat-6.0.14.tar.gz archive, for example, uncompress it wherever you want Tom- cat’s files to reside: $ cd $HOME $ tar zxvf apache-tomcat-6.0.14.tar.gz Installing Tomcat | 5 Before you go any further, you shouldbriefly look at the RELEASE-NOTES text file that resides in the root of your new Tomcat installation. It contains important informa- tion for everyone installing Tomcat andcan give you detailsspecific to the version you downloaded. Something else that is very important for you to do before proceeding with the installation is to readthe online Tomcat changelog for your branch of Tom- cat. For example, Tomcat 6.0’s online changelog is at http://tomcat.apache.org/ tomcat-6.0-doc/changelog.html. Regardless of the version of Tomcat you install and use, you shouldlook at the bugs listedin the changelog because bugs that exist in your version are fixedin newer versions of Tomcat andwill show up in the changelog listed under newer versions. Although Java 1.5.x runtimes work fine with Tomcat 6, it is suggestedthat you use Java 1.6.x. If you’ll be running Tomcat as user tomcat (or any user other than the one you log in as), you must install the files so that this user may readandwrite those files. After you have unpackedthe archives, you must set the file permissions on the Tomcat files so that the tomcat user has read/write permissions. To do that for a different user account, you’ll needroot (superuser) access again. Here’s one way to dothat from the shell: # chown -R tomcat apache-tomcat-6.0.14 Tomcat shouldnow be readyto run, although it will not restart on reboots. To learn how to make it run when your server computer boots up, see “Automatic Startup,” later in this chapter. Installing Tomcat from this book’s Linux RPM packages This book contains a production quality example of a Tomcat RPM package for Linux (see Appendix E for the source). It serves as both an elegant way to get Tom- cat installedandrunning on Linux andas an example of how you may buildyour own custom Tomcat RPM package. Before you begin, you must install Apache Ant (http://ant.apache.org) version 1.6.2 or higher (but not version 1.6.4—that release was broken), preferably 1.7.x or higher. It must be usable from the shell, like this: # ant -version Apache Ant version 1.7.0 compiled on December 13 2006 You must also have the rpmbuild binary available in your shell. In Fedora and Red Hat distributions, this is part of the RPM package named rpm-build. You must use version 4.2.1 or higher (the 4.2.0 version that is included with Red Hat 9 has a bug that prevents rpmbuild from working properly—but that is becoming antiquated!). Just make sure it’s installed and you can run the rpmbuild command successfully: # rpmbuild --version RPM version 4.3.2 6 | Chapter 1: Getting Started with Tomcat Downloadthis book’s examples archive from http://catalog.oreilly.com/examples/ 9780596101060. Unpack it like this: $ unzip tomcatbook-examples-2.0.zip Change directory into the tomcat-package directory: $ cd tomcatbook-examples/tomcat-package Now, download the binary release archives from the Apache binary releases page at http://tomcat.apache.org/download-60.cgi. You shoulddownloadthelatest stable ver- sion as listedon the Tomcat home page at http://tomcat.apache.org. Downloadall the tar.gz archive files for the version of Tomcat that you’ve chosen. Move all the Tomcat binary release archive files into the tomcatbook-examples/ tomcat-package/ directory so they can be included in the RPM package set you’re about to build: # cp apache-tomcat-6.0.14*.tar.gz tomcatbook-examples/tomcat-package/ Edit the conf/tomcat-env.sh file to match the setup of the machines where you’ll deploy your Tomcat RPM packages. At the minimum, you should make sure that JAVA_HOME is an absolute filesystem path to a Java 1.5 or 1.6 compliant virtual machine (either a JDK or a JRE). Then, invoke ant to build your Tomcat 6 RPM package set: $ ant This shouldbuildthe Tomcat RPM packages, andwhen the buildis complete, you will find them in the dist/ directory: # ls dist/ tomcat-6.0.14-0.noarch.rpm tomcat-6.0.14-0-src.tar.gz tomcat-6.0.14-0.src.rpm tomcat-6.0.14-0.tar.gz The Tomcat RPM package builder also builds a Tomcat source RPM package,* plus a tar.gz archive of the RPM package as a convenience. Copy the RPM package to the machine(s) you wish to install it on. When you’re ready to install it, you have two choices: • Install it into its default path of /opt/tomcat. • Install it, relocating it to a path of your choice. Here’s how to install it to the default path: * Think of this source RPM package as the content necessary to buildthe binary RPM package, not necessarily the Java source code to Tomcat itself. This book’s Tomcat RPM package was built using the officially com- piledTomcat class files, so the Java source isn’t includedinthe source RPM package, nor is it necessary to build the multiplatform “binary” RPM package. Installing Tomcat | 7 # rpm -ivh tomcat-6.0.14-0.noarch.rpm Preparing... ########################################### [100%] 1:tomcat ########################################### [100%] The following error: error: Failed dependencies: /bin/sh is needed by tomcat-6.0.14-0.noarch usually occurs on operating systems that do not primarily use the RPM package manager, andyou are installing this Tomcat RPM package when the RPM package manager’s database is empty (no package in the database provides the /bin/sh inter- preter). This may happen, for example, if you are installing the Tomcat RPM pack- age on a Debian Linux OS after installing the rpm command. Try to install it again like this: # rpm -ivh --nodeps tomcat-6.0.14-0.noarch.rpm If you get warnings such as these about users and groups: warning: user tomcat does not exist - using root warning: group nobody does not exist - using root you needto adda tomcat user and nobody group by handusing adduser and addgroup. Just make sure that the tomcat user’s primary group is nobody. Also, make sure that you set user tomcat’s home directory to “/opt/tomcat/temp,” andset tomcat’s login shell to something that doesn’t actually work, such as /sbin/nologin if you have that: # groupadd nobody # useradd -s /sbin/nologin -d /opt/tomcat/temp -c 'Tomcat User' \ -g nobody tomcat Once you are done with this, try again to install the tomcat package: # rpm -e tomcat # rpm -ivh --nodeps tomcat-6.0.14-0.noarch.rpm Once it’s installed, just verify that the JAVA_HOME path set in /opt/tomcat/conf/ tomcat-env.sh points to the 1.5 or 1.6 JVM that you want it to. That’s it! Tomcat should be ready to run. With these same RPM packages, you can install Tomcat andrelocate it to a different filesystem path, like this: # rpm -ivh --prefix /usr/local tomcat-6.0.14-0.noarch.rpm This wouldinstall Tomcat, relocating it so that CATALINA_HOME becomes /usr/ local/tomcat. You may install the admin and compat packages this way as well. As of this writing, JPackage.org does not offer a Tomcat 6 RPM pack- age, but instead offers a Tomcat 5.5 RPM package. 8 | Chapter 1: Getting Started with Tomcat Installing Tomcat from the JPackage.org Linux RPM packages To download and install the JPackage.org Tomcat RPM packages, visit http://JPackage. org/repos.php. This page discusses how to configure meta package managers, such as yum, apt-rpm, urpmi, and up2date. This is the only reasonable way to install the JPack- age.org Tomcat RPM package set due to its large number of installation dependencies. Also, because the details about how to set up the repository configuration for the meta package manager can change at any time, we are not able to show an example of how to do it in this book. See JPackage.org’s web site for the details. The JPackage.org Tomcat 5.5 RPM creates a user andgroup both named tomcat5 andruns Tomcat with that user andgroup. The default shell of the tomcat5 user is /bin/sh. Don’t try to change this or Tomcat will stop running correctly. Installing Tomcat on Solaris Before you install a new Tomcat package on Solaris, you shouldprobably inspect your system to find out if there is already one present and decide if you should remove it. By default, no Tomcat package should be installed, at least on Sun’s Solaris 10. Solaris 9 ships with an older version of Tomcat. Check to see if it’s installed: jasonb$ pkginfo | grep -i tomcat If this commandoutputs one or more packages, a version of Tomcat is installed. To get more information about the package, use pkginfo with the -l switch. For example, if the preinstalledTomcat package name was SUNWtomcat: jasonb$ pkginfo -l SUNWtomcat Even if Tomcat is installed, it should not cause problems. To be safe, we suggest that you uninstall an existing Tomcat package only if you’re preparedto dealwith any breakage that removal may cause. If you’re sure the package is causing you problems, as the root user, you can remove it: # pkgrm SUNWtomcat To install a Tomcat Solaris package, you needto set your user identityto the root user or else you will not have sufficient permissions to write the files. Usually, this is done either with the sudo or su commands. For example: # su - Password: Sun Microsystems Inc. SunOS 5.10 Generic January 2005 # id uid=0(root) gid=0(root) Then, you can proceed with the installation. Installing Tomcat | 9 Solaris already comes standard with Java 1.5.0, but you should make sure to upgrade it to a newer, more robust version. See Appendix A for details on what to get and where to get it. As of this writing, the only Solaris package of Tomcat that we couldfindis a Tomcat 5.5 package included in the Blastwave Solaris Community Software (CSW) package set. This package set is a community supportedset of open source packages, analo- gous to a Linux distribution’s package set. See the Blastwave CSW page about it at http://www.blastwave.org. The CSW package is best installedvia the pkg-get com- mand. This command does not come with Solaris, but it is easy to install. Install pkg-get from the URL http://www.blastwave.org/pkg-get.php. we were able to use wget to download it like this: # PATH=/opt/csw/bin:/usr/sfw/bin:/usr/sfw/sbin:$PATH # export PATH # wget http://www.blastwave.org/pkg_get.pkg If that doesn’t work (for example, you don’t have wget installed), just use a web browser to download the pkg_get.pkg file to your Solaris machine. Install the pkg_get package like this: # pkgadd -d pkg_get.pkg And hit enter or answer y at the prompts. Now, add the path setting to the system’s /etc/default/login file. First, make it writable by root: # chmod u+w /etc/default/login Then, edit /etc/default/login and add this: PATH=/opt/csw/bin:/usr/sfw/bin:/usr/sfw/sbin:$PATH export PATH Then, save the file and put the permissions back: # chmod u-w /etc/default/login Do the same with /etc/profile, except you shouldn’t need to modify its file permis- sions. Edit /etc/profile and insert the same lines at the end of the file, and then save it. Before using pkg-get, update pkg-get’s catalog, like this: # pkg-get -U Once that’s done, you can install packages using pkg-get. Once you have the pkg-get commandinstalledandworking, you can install Tomcat 5.5. Make sure to switch to the root user; you can install packages from there. Install Tomcat’s package like this: # pkg-get install tomcat5 10 | Chapter 1: Getting Started with Tomcat There is no CSW package for Tomcat 5.0, so the Tomcat 5.5 package is called CSWtomcat5. If it tells you that some of the scripts must run as the superuser andasks you if you are sure you want to install the packages, just type y and hit enter. Installing the CSWtomcat5 package also starts it. When the installa- tion is complete, you’re already running Tomcat! Test it at the URL http://localhost:8080. Once it is installed, the base install directory is /opt/csw/share/tomcat5, andthe init script is installedas /etc/init.d/cswtomcat5. When you first get this Tomcat package installed, you should read the comments at the top of the init script to learn details about your Solaris Tomcat package. The details can change with each revision of the package. Installing Tomcat on Windows For Windows systems, Tomcat is available as a Windows-style graphical installer that is available directly from the Apache Software Foundation’s Tomcat downloads page. Although you can also install Tomcat from a zippedbinary release, the Win- dows graphical installer does a lot of setup and operating system integration for you as well, and we recommend it. Start by downloading an installer release, such as apache-tomcat-6.0.14.exe (or later; unless there is a goodreason not to, use the lat- est available stable version), from the release page at http://tomcat.apache.org/ download-60.cgi. When you download and run this installer program, it will first verify that it can find a JDK andJRE, andthen prompt you with a license agreement. This license is the Apache Software License, which allows you to do pretty much anything with the software as long as you give credit where it’s due. Accept the license as shown in Figure 1-1. Next, the installer will allow you to select which Tomcat components to install. At the top of the installer window, there is a handy drop-down list from which you can select a different typical packaged set of components (see Figure 1-2). To hand select which components to install, choose Custom in the drop-down list, and you may select and deselect any component or subcomponent. If you want to have Tomcat startedautomatically andbe able to control it from the Services Control Panel, check the box to install the Service software. Then, specify where to install Tomcat. The default is in C:\Program Files\Apache Software Foundation\Tomcat 6.0. Change it if you want, as shown in Figure 1-3. Installing Tomcat | 11 Figure 1-1. The Tomcat installer for Windows: accepting Tomcat’s Apache license Figure 1-2. Windows choosing Tomcat components to install 12 | Chapter 1: Getting Started with Tomcat Next, the installer will prompt you for the HTTP/1.1 connector port—this is Tom- cat’s web server port. By default it is set to port 8080, but on Windows feel free to change it to 80 if you want Tomcat to be your first contact web server (Tomcat does a wonderful job in that role). The installer also asks for the administrator login user- name andpasswordto set for Tomcat. Set the passwordto something that will not be easily guessed, but don’t forget what it is! That will be your username and password to log into Tomcat’s Manager webapp. The installer then allows you to choose a Java runtime for Tomcat from the runtimes you have installedat that time. We suggest Java 1.6.x or higher for this. Once you have configuredit with a Java runtime, the Install button becomes clickable. Click it and the installer will begin installing Tomcat. Once the installation completes normally, you shouldsee the message “Completing the Apache Tomcat Setup Wizard” at the end, as shown in Figure 1-4. From the installer, you can select to start Tomcat andclick Finish. Then, in your web browser, type in the URL to your Tomcat, such as http://localhost:8080, andyou should see the Tomcat start page as shown in Figure 1-5. Congratulations! Your new Tomcat is installedandreadyto use. You now needto start the server for initial testing, as described in the upcoming section “Starting, Stopping, and Restarting Tomcat.” Figure 1-3. Windows installation directory Installing Tomcat | 13 Figure 1-4. Windows installation of Tomcat is complete Figure 1-5. Testing Apache Tomcat 14 | Chapter 1: Getting Started with Tomcat Installing Tomcat on Mac OS X Thanks to the wonderful BSD underpinnings of Mac OS X, installing Tomcat on Mac OS X is similar to the non-RPM Linux installation you have seen. When installing on Mac OS X, you shoulddownloadthe .tar.gz file rather than the .zip file from the Tom- cat site as Unix file permissions are not properly preservedin zip files. In particular, execute permission is lost on the scripts included with Tomcat, making it impossible to start or stop Tomcat until the permissions are restored. Before choosing which version of Tomcat to install, you need to check your Java version as shown below: $ java -version java version "1.5.0_07" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_07-164) Java HotSpot(TM) Client VM (build 1.5.0_07-87, mixed mode, sharing) If your Java version is at least 1.5.0, you can install Tomcat 5.5 or Tomcat 6.0. If you do not have a Java runtime of at least version 1.5.0, you cannot install Tomcat 6.0 or higher without first updating Java. If you are running a fully updated version of OS X 10.4 (Tiger) or higher, you have a minimum Java version of 1.5.0. You can down- loadit from the Apple Developer Connection at http://connect.apple.com. Register if you have not (it’s free!), and then navigate to the Java downloads section; this can also be done via Apple’s Software Update. Please ensure that you are installing the latest version of the JDK from Apple. By the time you readthis, Apple’s 1.6 JDK will almost certainly be available, and we encourage you to install and use it. These instructions rely on the use of the sudo command. On OS X, you must be logged in as a user with administrative privileges to use this command. sudo executes a single commandas a differentuser. These instructions use sudo to execute com- mands as the users root and nobody. You shouldnote that when sudo asks for a pass- word, you should enter your login password, not the password for the user you are executing the command as, like you would with the su command. These instructions will install Tomcat to /usr/local/. There is some debate as to the more appropriate place to install Linux or BSD style programs on OS X with some preferring to use /Library/ rather than /user/local/. As on Linux, it is advisable to install Tomcat to run as a nonprivileged user. Some people like to create a special user just for Tomcat, but that is not necessary. It is simpler to use the built-in nobody user instead. These instructions use this preexist- ing user rather than create a new user. Once you have downloaded the .tar.gz file for your chosen version from the Tomcat site, you need to extract it. You can do this from the Finder or from the Terminal as follows (replacing the filename as appropriate): $ tar -xzf apache-tomcat-6.0.14.tar.gz Installing Tomcat | 15 Once you have downloaded and extracted Tomcat, you need to move the files to the folder you are installing to; again you can do this from the Finder, but because we’ll needto use the Terminal for the remainderof these instructions, you may as well use it here for this step too. Once you have changedinto the foldercontaining the files you extractedfrom the .tar.gz file, you needto run the following (replacing the file- name as needed): $ sudo mv apache-tomcat-6.0.14 /usr/local/ Enter your login password, and the directory will be relocated to /usr/local. To simplify future upgrades, you should create a symbolic link from /usr/local/tomcat to the folder you have just moved to /usr/local/, as follows (again replacing the file- name as appropriate): $ sudo ln -s /usr/local/apache-tomcat-6.0.14/ /usr/local/tomcat Tomcat requires two environment variables to run: JAVA_HOME and CATALINA_ HOME. JAVA_HOME specifies the Java Virtual Machine to be usedby Tomcat, and CATALINA_HOME specifies the root directory of the unpacked Tomcat binary (runtime) distribution. They should be set by adding the following lines to the end of /etc/profile with your favorite text editor (e.g., sudo vi /etc/profile): export JAVA_HOME=/Library/Java/Home export CATALINA_HOME=/usr/local/tomcat The above assumes that you are using the default JVM for your version of OS X. If you wish to use a different JVM, you’ll have to change the value for JAVA_HOME. Because /etc/profile is only readwhen a Terminal is opened,you shouldclose your Terminal andopen a new one at this point. You can check that the variables have been set properly as follows: $ echo $JAVA_HOME /Library/Java/Home $ echo $CATALINA_HOME /usr/local/tomcat Later, if you decide to use launchd for starting andstopping Tomcat, as we show you below, you do not need the environment variable defi- nitions in /etc/profile. You’re almost done now; you just need to change the ownership of your Tomcat install to the user nobody: $ sudo chown -R nobody:nobody /usr/local/tomcat $ cd /usr/local $ ls -l total 0 drwxr-x--- 13 nobody nobody 442 Sep 27 15:36 apache-tomcat-6.0.14 16 | Chapter 1: Getting Started with Tomcat Notice that Tomcat is now by owned nobody andhas very restrictive permissions for execution. Tomcat shouldnow be readyto run, although it will not restart on reboots. To see how to make Tomcat run when your server computer boots up, see the upcoming section “Automatic Startup.” Installing Tomcat on FreeBSD The FreeBSD ports system includes a port of Tomcat 6. See http://www.freshports. org/www/tomcat6/ for more up-to-date details about it. First, make sure you update your Tomcat 6 port tree. Here’s how: # cd /root # cp /usr/share/examples/cvsup/ports-supfile tc6-supfile Edit the tc6-supfile. See the endof the page http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/ cvsup.html to find the best default host name to use for your geographical location. Now, use the modified supfile to update the tree: # pkg_add -r cvsup # cvsup -g -L 2 tc6-supfile Once the tree is up to date, install it like this: # cd /usr/ports/www/tomcat-6 # make install This does not build Tomcat from its source code. Instead, it “builds” the FreeBSD ports package files by extracting the official Apache binary release archives, and adds FreeBSD-specific packaging files, andthen installs them all where they shouldbe installed on FreeBSD. When that is done, edit your /etc/rc.conf file andaddthese lines to the end: tomcat60_enable="YES" tomcat60_java_opts="-Djava.net.preferIPv4Stack=true" The first line enables the RCng init script—this init script has code that will not try to start Tomcat unless the tomcat60_enable variable is enabledthis way, to prevent Tomcat from accidentally starting at boot time. Adding the second line will avoid a problem that prevents Tomcat from opening its TCP server ports. Change the lines that say: To say: *default host=CHANGE_THIS.FreeBSD.org *default host=cvsup.FreeBSD.org ports-all #ports-all #ports-www ports-www Starting, Stopping, and Restarting Tomcat | 17 Starting, Stopping, and Restarting Tomcat Once you have the installation completed, you will probably be eager to start Tom- cat andsee if it works. This section detailshow to start up andshut downTomcat, including specific information on each supported operating system. It also details common errors that you may encounter, enabling you to quickly identify and resolve any problems you run into. Starting Up and Shutting Down The correct way to start and stop Tomcat depends on how you installed it. For example, if you installedTomcat from a Linux RPM package, you shoulduse the init script that came with that package to start andstop Tomcat. Or, if you installed Tomcat on Windows via the graphical installer from tomcat.apache.org, you should start andstop Tomcat as you wouldany Windowsservice. Details about each of these package-specific cases are given in the next several sections. If you installed Tomcat by downloading the binary release archive (.zip or .tar.gz) from the Tomcat downloads page—what we’ll call the generic installation case—you should use the command-line scripts that reside in the CATALINA_HOME/bin directory. There are several scripts in the bin directory that you will use for starting and stop- ping Tomcat. All the scripts you will need to invoke directly are provided both as shell script files for Unix (.sh) andbatch files for Windows( .bat). Table 1-1 lists these scripts anddescribeseach. When referring to these, we have omittedthe file- name extension because catalina.bat has the same meaning for Microsoft Windows users that catalina.sh* has for Unix users. Therefore, the name in the table appears simply as catalina. You can infer the appropriate file extension for your system. * Linux, BSD, andUnix users may object to the .sh extension for all of the scripts. However, renaming these to your preferredconventions is only temporary, as the .sh versions will reappear on your next upgrade. You are better off getting used to typing catalina.sh. Table 1-1. Tomcat invocation scripts Script Purpose catalina The main Tomcat script. This runs the java command to invoke the Tomcat startup and shutdown classes. cpappend This is used internally, and then only on Windows systems, to append items to Tomcat classpath envi- ronment variables. digest This makes a crypto digest of Tomcat passwords. Use it to generate encrypted passwords. service This script installs and uninstalls Tomcat as a Windows service. setclasspath This is also only used internally and sets the Tomcat classpath and several other environment variables. shutdown This runs catalina stop and shuts down Tomcat. startup This runs catalina start and starts up Tomcat. 18 | Chapter 1: Getting Started with Tomcat The main script, catalina, is invokedwith one of several arguments. The most com- mon arguments are start, run,orstop. When invokedwith start (as it is when calledfrom startup), it starts up Tomcat with the standard output and standard error streams directed into the file CATALINA_HOME/logs/catalina.out. The run argu- ment causes Tomcat to leave the standard output and error streams where they cur- rently are (such as to the console window) useful for running from a terminal when you want to see the startup output. This output should look similar to Example 1-1. tool-wrapper This is a generic Tomcat command-line tool wrapper script that can be used to set environment vari- ables and then call the main method of any fully qualified class that is in the classpath that is set. This is used internally by the digest script. version This runs the catalina version, which outputs Tomcat’s version information. Example 1-1. Output from catalina run ian:389$ bin/catalina.sh start Using CATALINA_BASE: /home/ian/apache-tomcat-6.0.14 Using CATALINA_HOME: /home/ian/apache-tomcat-6.0.14 Using CATALINA_TMPDIR: /home/ian/apache-tomcat-6.0.14/temp Using JRE_HOME: /usr/java/jdk1.6.0_02 Sep 27, 2007 10:42:16 PM org.apache.catalina.core.AprLifecycleListener lifecycleEvent INFO: The Apache Tomcat Native library which allows optimal performance in produ ction environments was not found on the java.library.path: /usr/java/jdk1.5.0_06/bin/../jre/bin: /usr/lib Sep 27, 2007 10:42:17 PM org.apache.coyote.http11.Http11BaseProtocol init INFO: Initializing Coyote HTTP/1.1 on http-8080 Sep 27, 2007 10:42:17 PM org.apache.catalina.startup.Catalina load INFO: Initialization processed in 948 ms Sep 27, 2007 10:42:17 PM org.apache.catalina.core.StandardService start INFO: Starting service Catalina Sep 27, 2007 10:42:17 PM org.apache.catalina.core.StandardEngine start INFO: Starting Servlet Engine: Apache Tomcat/6.0.14 Sep 27, 2007 10:42:17 PM org.apache.catalina.core.StandardHost start INFO: XML validation disabled Sep 27, 2007 10:42:27 PM org.apache.coyote.http11.Http11BaseProtocol start INFO: Starting Coyote HTTP/1.1 on http-8080 Sep 27, 2007 10:42:28 PM org.apache.jk.common.ChannelSocket init INFO: JK: ajp13 listening on /0.0.0.0:8009 Sep 27, 2007 10:42:29 PM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/106 config=null INFO: Find registry server-registry.xml at classpath resource Sep 27, 2007 10:42:30 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 1109 ms Table 1-1. Tomcat invocation scripts (continued) Script Purpose Starting, Stopping, and Restarting Tomcat | 19 If you use catalina with the start option or invoke the startup script insteadof using the run argument, you see only the first few Using... lines on your console; all the rest of the output is redirected into the catalina.out logfile. The shutdown script invokes catalina with the argument stop, which causes Tomcat to connect to the default port specified in your Server element (discussed in Chapter 7) and send it a shutdown message. A complete list of startup options is listed in Table 1-2. Environment variables To prevent runaway programs from overwhelming the operating system, Java run- time environments feature limits such as “maximum heap size.” These limits were establishedwhen memory was more expensive than at present; for JDK 1.3, for example, the default limit was only 32 MB. However, there are options supplied to the java command that let you control the limits. The exact form depends upon the Java runtime, but if you are using the Sun runtime, you can enter: java -Xmx=256M MyProg This will run a class file called MyProg with a maximum memory size of 256 MB for the entire Java runtime process. These options become important when using Tomcat, as running servlets can begin to take up a lot of memory in your Java environment. To pass this or any other option into the java commandthat is usedto start Tomcat, you can set the option in the envi- ronment variable JAVA_OPTS before running one of the Tomcat startup scripts. Table 1-2. Startup options Option Purpose -config [server.xml file] This specifies an alternate server.xml configuration file to use. The default is to use the server.xml file that resides in the $CATALINA_BASE/conf directory. See the “server.xml” section in Chapter 7 for more information about server.xml’s contents. -help This prints out a summary of the command-line options. -nonaming This disables the use of JNDI within Tomcat. -security This enables the use of the catalina.policy file. debug This starts Tomcat in debugging mode. embedded This allows Tomcat to be tested in an embedded mode, and is usually used by appli- cation server developers. jpda start This starts Tomcat as a Java Platform Debugger Architecture-compliant debugger. See Sun’s JPDA documentation at http://java.sun.com/products/jpda. run This starts up Tomcat without redirecting the standard output and errors. start This starts up Tomcat, with standard output and errors going to the Tomcat logfiles. stop This stops Tomcat. version This outputs Tomcat’s version information. 20 | Chapter 1: Getting Started with Tomcat Windows users should set this environment variable from the Control Panel, and Unix users should set it directly in a shell prompt or login script: $ export JAVA_OPTS="-Xmx256M" # Korn and Bourne shell C:\> set JAVA_OPTS="-Xmx256M" # MS-DOS $ setenv JAVA_OPTS "-Xmx256M" # C-shell Other Tomcat environment variables you can set are listed in Table 1-3. Starting and stopping: The general case If you have installedTomcat via an Apache binary release archive (either a .zip file or a .tar.gz file), change directory into the directory where you installed Tomcat: $ cd apache-tomcat-6.0.14 Echo your $JAVA_HOME environment variable. Make sure it’s set to the absolute path of the directory where the Java installation you want Tomcat to use resides. If it’s not, set it andexport it now. It’s OK if the java interpreter is not on your $PATH because Tomcat’s scripts are smart enough to findanduse Java basedon your set- ting of $JAVA_HOME. Table 1-3. Tomcat environment variables Option Purpose Default CATALINA_BASE This sets the base directory for writable or customized portions of a Tomcat installation tree, such as logging files, work directo- ries, Tomcat’s conf directory, and the webapps directory. It is an alias for CATALINA_HOME. Tomcat installation directory CATALINA_HOME This sets the base directory for static (read-only) portions of Tomcat, such as Tomcat’s lib directories and command-line scripts. Tomcat installation directory CATALINA_OPTS This passes through Tomcat-specific command-line options to the java command. None CATALINA_TMPDIR This sets the directory for Tomcat temporary files. CATALINA_HOME/temp JAVA_HOME This sets the location of the Java runtime or JDK that Tomcat will use. None JRE_HOME This is an alias to JAVA_HOME. None JAVA_OPTS This is where you may set any Java command-line options. None JPDA_TRANSPORT This variable may set the transport protocol used for JPDA debugging. dt_socket JPDA_ADDRESS This sets the address for the JPDA used with the catalina jpda start command. 8000 JSSE_HOME This sets the location of the Java Secure Sockets Extension used with HTTPS. None CATALINA_PID This variable may optionally hold the path to the process ID file that Tomcat should use when starting up and shutting down. None Starting, Stopping, and Restarting Tomcat | 21 Make sure you’re not running a TCP server on port 8080 (the default Tomcat HTTP server socket port), nor on TCP port 8005 (the default Tomcat shutdown server socket port). Try running telnet localhost 8080 and telnet localhost 8005 to see if any existing server accepts a connection, just to be sure. Start up Tomcat with its startup.sh script like this: $ bin/startup.sh Using CATALINA_BASE: /home/jasonb/apache-tomcat-6.0.14 Using CATALINA_HOME: /home/jasonb/apache-tomcat-6.0.14 Using CATALINA_TMPDIR: /home/jasonb/apache-tomcat-6.0.14/temp Using JAVA_HOME: /usr/java/jdk1.6.0_02 You shouldsee output similar to this when Tomcat starts up. Once started,it should be able to serve web pages on port 8080 (if the server is localhost, try http://localhost: 8080 in your web browser). Invoke the shutdown.sh script to shut Tomcat down: $ bin/shutdown.sh Using CATALINA_BASE: /home/jasonb/apache-tomcat-6.0.14 Using CATALINA_HOME: /home/jasonb/apache-tomcat-6.0.14 Using CATALINA_TMPDIR: /home/jasonb/apache-tomcat-6.0.14/temp Using JAVA_HOME: /usr/java/jdk1.6.0_02 Starting and stopping on Linux If you’ve installedTomcat via the RPM package on Linux, you can test it out by issu- ing a start command via Tomcat’s init script, like this: # /etc/rc.d/init.d/tomcat start Starting tomcat: [ OK ] Or, on some Linux distributions, such as Fedora and Red Hat, to do the same thing, you may instead type the shorter command: # service tomcat start If you installedthe JPackage.org Tomcat RPM package, the name of the init script is tomcat55, so the command would be: # /etc/rc.d/init.d/tomcat55 start Then, check to see if it’s running: # ps auwwx | grep catalina.startup.Bootstrap You shouldsee several Java processes scroll by. Another way to see whether Tomcat is running is to request a web page from the server over TCP port 8080. If Tomcat fails to startup correctly, go back andmake sure that the /opt/ tomcat/conf/tomcat-env.sh file has all the right settings for your server computer (in the JPackage.org RPM installation case, it’s the /etc/ tomcat55/tomcat55.conf file). Also check out the “Common Errors” sec- tion, later in this chapter. 22 | Chapter 1: Getting Started with Tomcat To stop Tomcat, issue a stop command like this: # /etc/rc.d/init.d/tomcat stop Or (shorter): # service tomcat stop Starting and stopping on Solaris To use Tomcat’s init script on Solaris, you must be the root user. Switch to root first. Then, you can start Tomcat like this: # /etc/init.d/cswtomcat5 start And, you can stop it like this: # /etc/init.d/cswtomcat5 stop Watch your catalina.out logfile in /opt/csw/share/tomcat5/logs so that you’ll know if there are any errors. Starting and stopping on Windows On Microsoft Windows, Tomcat can be started and stopped either as a windows ser- vice or by running a batch file. If you arrange for automatic startup (detailed later in this chapter), you may manually start Tomcat in the control panel. If not, you can start Tomcat from the desktop icon. If you have Tomcat running in a console window, you can interrupt it (usually with Ctrl-C) and it will catch the signal and shut down: Apache Tomcat/6.0.14 ^C Stopping service Tomcat-Standalone C:\> If the graceful shutdown does not work, you need to find the running process and ter- minate it. The JVM running Tomcat will usually be identified as a Java process; be sure you get the correct Java if other people or systems may be using Java. Use Ctrl-Alt- Delete to get to the task manager, select the correct Java process, andclick on End Task. Starting and stopping on Mac OS X The Mac OS X installation of Tomcat is simply the binary distribution, which means you can use the packagedshell scripts that come with the Apache binary release. This provides a quick and easy set of scripts to start and stop Tomcat as required. First, we will show you the general case for starting and stopping Tomcat on Mac OS X. Mac OS X sets all your paths for you so all you needto dois ensure that there are no TCP services already running on port 8080 (the default Tomcat HTTP server socket Starting, Stopping, and Restarting Tomcat | 23 port), nor on port 8005 (the default Tomcat shutdown port). This can be done easily by running the netstat command: $ netstat -an | grep 8080 You shouldsee no output. If you do,it means another program is listening on port 8080, andyou shouldshut it downfirst, or you must change the port numbers in your CATALINA_HOME/conf/server.xml configuration file. Do the same for port 8005. Tomcat can be started on OS X with the following command: $ cd /; sudo -u nobody /usr/local/tomcat/bin/startup.sh; cd - Tomcat can be stopped with the following command: $ cd /; sudo -u nobody /usr/local/tomcat/bin/shutdown.sh; cd - Because the user nobody is an unprivileged user, a lot of folders on your disk are not accessible to it. This is of course a goodthing, but because the scripts for starting and stopping Tomcat attempt to determine the current directory, you will get errors if the scripts are not being calledfrom a folderto which the user nobody has readaccess. To avoid this, the above commands consist of three subcommands. First, they change to the root folder (/), next they call script to start or stop Tomcat as the user nobody, and finally they return to the folder they started in. If you are running the commands from a folder to which the user nobody has readaccess (e.g., /), you can shorten the com- mands by leaving out the first and last parts as follows: $ sudo -u nobody /usr/local/tomcat/bin/startup.sh $ sudo -u nobody /usr/local/tomcat/bin/shutdown.sh Later in the “Automatic Startup on Mac OS X” section, we show you how to create andinstall init scripts via Apple’s launchd, as you see in the Linux RPM installa- tions andthe BSD port installs, to allow you to not only start andstop Tomcat, but also to automatically start Tomcat on boot—the Mac OS X way! Starting and stopping on FreeBSD This port installs Tomcat into the root path /usr/local/tomcat6.0/. The behavior of Tomcat may be configuredthrough variables in your /etc/rc.conf file, which override settings that are containedin the /etc/defaults/rc.conf file. This port includes an RCng script named ${PREFIX}/etc/rc.d/tomcat60.sh. By default, this ends up being /usr/ local/etc/rc.d/tomcat60.sh. Readthe top of this file to see what Tomcat variable set- tings you may apply in your /etc/rc.conf file. Try starting Tomcat like this: # /usr/local/etc/rc.d/tomcat60.sh start Starting tomcat60. This will only work if you have added this line to your /etc/rc.conf file: tomcat60_enable="YES" You may use the tomcat60.sh script to start, stop, and restart Tomcat 6. 24 | Chapter 1: Getting Started with Tomcat By default, this FreeBSD port of Tomcat 6.0 sets Tomcat’s default HTTP port to be 8180, which is different than the default that is originally set (for all operating sys- tems) in the Apache Software Foundation’s distribution of Tomcat (which is 8080). Try accessing your FreeBSD Tomcat port via the URL http://localhost:8180/. Common Errors Several common problems can result when you try to start up Tomcat. While there are many more errors that you can run into, these are the ones we most often encounter. Another server is running on port 80 or 8080 Ensure that you don’t have Tomcat already started. If you don’t, check to see if other programs, such as another Java application server or Apache Web Server, are running on these ports. Another instance of Tomcat is running Remember that not only must the HTTP port of different Tomcat instances (JVMs) be different, every port number in the Server and Connector elements in the server.xml files must be different between instances. For more information on these elements, consult Chapter 7. Restarting Tomcat At the time of this writing, there is no restart script that is part of the Tomcat 6.0 dis- tribution because it is tough to write a script that can make sure that when Tomcat stops, it shuts down properly before being started up again. The reasons outlined below for Tomcat shutdowns being unreliable are almost exclusively edge condi- tions. That means they don’t usually happen, but that they can occur in unusual situ- ations. Here are some reasons why shutdowns may be unreliable: • The Java Servlet Specification does not mandate any time limit for how long a Java servlet may take to perform its work. Writing a servlet that takes forever to perform its work does not break compliance with the Java Servlet Specification, but it can prevent Tomcat from shutting down. • The Java Servlet Specification also dictates that on shutdowns, servlet contain- ers must wait for each servlet to finish serving all requests that are in progress before taking the servlet out of service, or wait a container-specific timeout dura- tion before taking servlets out of service. For Tomcat 6, that timeout duration is a maximum of a half-secondper servlet. When a servlet misbehaves andtakes too long to finish serving requests, it’s up to Tomcat to figure out that the serv- let has taken too long andforcibly take it out of service so that Tomcat can shut down. This processing takes time, though, and slows Tomcat’s own shutdown processing. Starting, Stopping, and Restarting Tomcat | 25 • Multithreading in Java virtual machines is specified in a way that means that Java code will not always be able to tell exactly how much real time is going by (Java SE is not a real-time programming environment). Also, due to the way Java threads are scheduled on the CPU, threads can become blocked and stay blocked. Because of these limitations, the Java code that is called on invocations of shutdown.sh will not always know how long to wait for Tomcat to shut down, nor can Tomcat always know it’s taking too long to shut down. That means that shutdowns are not completely reliable when written in pure Java. An external program wouldneedto be written in some other programming language to reli- ably shut down Tomcat. • Because Tomcat is an embeddable servlet container, it tries not to call System. exit(0) when shutting down the server because Tomcat does not know what else may needto stay running in the same Java virtual machine. Instead,Tomcat shuts down all of its own threads so that the VM can exit gracefully if nothing else needs to run. Because of that, a servlet could spawn a thread that would keep the VM from exiting even when Tomcat’s threads are all shut down. • The Java Servlet Specification allows servlets to create additional Java threads that perform work as long as any security manager allows it.* Once another threadis spawnedfrom a servlet, it can raise its own priority higher than Tom- cat’s threads’ priorities (if the security manager allows) and could keep Tomcat from shutting down or from running at all. Usually if this happens, it’s not mali- cious code but buggy code. Try not to do this! • If your Tomcat instance has run completely out of memory (as evidenced by the dreaded “Permgen memory” error in the logs), it will usually be unable to accept new connections on its web port or on its shutdown port. To fix some of the problems, you may want to configure anduse a security manager. See Chapter 6 for more information on how to place limits on webapps to guard against some of these problems. The general case If you installed Tomcat “by hand” by downloading and unpacking an official binary release archive (tar.gz or .zip) from tomcat.apache.org, regardless of the operating system you’re using, here is the standard way to restart Tomcat: 1. Change directory into the root of the Tomcat installation directory (commonly known as the CATALINA_HOME directory): $ cd apache-tomcat-6.0.14 * An urban legend about developing Java webapps says that according to the Java Servlet Specification, serv- lets in webapps are not allowed to spawn any Java threads. That is false. The servlet specification does not preclude doing this, so it is OK to spawn one or more threads as long as the thread(s) are well behaved. This is often the rub, since webapp developers often report bugs against Tomcat that turn out to be caused by their own code running in a separate thread. 26 | Chapter 1: Getting Started with Tomcat 2. Issue a shutdown via the shutdown.sh script: $ bin/shutdown.sh 3. Decide how long you want to wait for Tomcat to shut down gracefully, and wait that period of time. Reasonable maximum shutdown durations depend on your web application, your server computer’s hardware, and how busy your server computer is, but in practice, Tomcat often takes several seconds to completely shut down. 4. Query your operating system for java processes to make sure it shut down. On Windows, hit Ctrl-Alt-Delete to get to the task manager, and scroll through the list to look for it. On all other operating systems, use the jps commandto look for any remaining Tomcat processes that are your Tomcat’s Java virtual machine. The jps command comes with Java. Try this: $ jps | grep Bootstrap If that fails, use an OS-dependent Process Status (ps) command, such as this: $ ps auwwx | grep catalina.startup.Bootstrap \ # On Linux or *BSD $ /usr/ucb/ps auwwx | grep catalina.startup.Bootstrap \ # On Solaris 5. If no Tomcat java processes are running, skip to step 6. Otherwise, because the Tomcat JVM is not shutting down in the time you’ve allowed, you may want to force it to exit. Senda TERM signal to the processes you find, asking the JVM to perform a shutdown (ensuring you have the correct user permissions): $ kill -TERM 6. Do another ps like you did in step 4. If the Tomcat JVM processes remain, repeat step 5 until they’re gone. If they persist, have your operating system kill the java process. On Windows, use the task manager to end the task(s). On all other operating systems, use the kill commandto tell the kernel to kill the process(es) like this: $ kill -KILL 7. Once you’re sure that Tomcat’s JVM is no longer running, start a new Tomcat process: $ bin/startup.sh Usually, the shutdown process goes smoothly and Tomcat JVMs shut down quickly. But, because there are situations when they don’t, the above procedure should always suffice. We realize this is not a very convenient way to restart Tomcat; how- ever, if you try to cut corners here, you will likely not always shut down Tomcat and get errors due to the new Tomcat JVM bumping into the existing Tomcat JVM when you go to start it again. Luckily, for most operating systems, there are scripts that automate this entire procedure, implemented as a “restart” command. You’ll find these integratedinto most OS-specific Tomcat installation packages (Linux RPM packages, the FreeBSD port, etc.). Starting, Stopping, and Restarting Tomcat | 27 Restarting Tomcat on Linux The following outlines how to reliably restart Tomcat on Linux. If you have installed Tomcat via an RPM package, either the one from this book or the one from JPackage. org, restarting Tomcat is easy. If you installed the RPM package from this book, do: # service tomcat restart And, if you installed the JPackage.org RPM package, do: # service tomcat55 restart which shouldreliably restart Tomcat. Be sure to check your logfiles for any startup problems. Restarting Tomcat on Solaris The following outlines how to reliably restart Tomcat on Solaris. If you have installed Tomcat via a Blastwave Solaris CSW package, restarting Tomcat is easy: # /etc/init.d/cswtomcat5 restart That should restart Tomcat. Be sure to check your logfiles for any startup problems. As of this writing, the Blastwave package’s init script does not contain any code to reliably restart Tomcat—it does not watch the processes to make sure that they came down all the way, nor does it try to force the processes down if they do not come down on their own. Readthe init script source andyou’ll see what we mean. So, it is up to the Solaris administrator to ensure (by hand) that the restart actually occurred. Restarting the Tomcat Windows Service If you have Tomcat running as a Windows Service, you can restart it from the con- trol panel. Either right-click on the service andselect Restart from the pop-up menu or, if it exists on your version of Windows, use the Restart button near the upper- right corner of the dialog box (see Figure 1-6). Be sure to check your logfiles for any startup problems. Restarting Tomcat on Mac OS X The standard way to restart Tomcat on OS X is to stop and then start Tomcat. If you have chosen to use the generic way to start Tomcat, there is no easy way to restart Tomcat in Mac OS X andthe best solution is to call shutdown.sh. Then, just as described in the Linux section of this chapter, you would decide how long you will wait for Tomcat to shut down and take the appropriate steps, as outlined above. A simple way to see if Tomcat is running is to check if there is a service listening on TCP port 8080 with the netstat command. This will, of course, only work if you are running Tomcat on the port you specify (its default port of 8080, for example) and not running any other service on that port. 28 | Chapter 1: Getting Started with Tomcat First, shut down the currently running Tomcat instance: $ netstat -an | grep 8080 tcp46 0 0 *.8080 *.* LISTEN $ cd /; sudo -u nobody /usr/local/tomcat/bin/shutdown.sh; cd - Using CATALINA_BASE: /usr/local/tomcat Using CATALINA_HOME: /usr/local/tomcat Using CATALINA_TMPDIR: /usr/local/tomcat/temp Using JRE_HOME: /Library/Java/Home/Users/bart Then, check to make sure Tomcat is no longer running: $ netstat -an | grep 8080 You shouldsee no output, meaning that Tomcat has shut down.Then, you may start it back up again, like this: $ cd /; sudo -u nobody /usr/local/tomcat/bin/startup.sh; cd - Using CATALINA_BASE: /usr/local/tomcat Using CATALINA_HOME: /usr/local/tomcat Using CATALINA_TMPDIR: /usr/local/tomcat/temp Using JRE_HOME: /Library/Java/Home/Users/bart After waiting some seconds, check to make sure that Tomcat is running and listen- ing on port 8080 again: $ netstat -an | grep 8080 tcp46 0 0 *.8080 *.* LISTEN Figure 1-6. Restart button in Control Panel Automatic Startup | 29 If you have chosen to use the automatic startup andshutdownscripts for Tomcat via Apple’s launchd (see the section “Automatic Startup on Mac OS X,” later in this chapter, for details about how to set that up), it’s very easy to restart Tomcat simply by unloading the service and reloading it into launchd: $ sudo launchctl unload /Library/LaunchDaemons/tomcat.plist $ sudo launchctl load /Library/LaunchDaemons/tomcat.plist Restarting Tomcat on FreeBSD The following outlines how to reliably restart Tomcat on FreeBSD. You can restart the Tomcat 6 port by running: # /usr/local/etc/rc.d/tomcat60.sh restart That shouldreliably restart Tomcat. Be sure to check your logfiles for any startup problems. Automatic Startup Once you have Tomcat installedandrunning, you can set it to start automatically when your system reboots. This will ensure that every time your system comes up, Tomcat will be running andhandlingrequests. Unix users will make changes to their init scripts, andWindowsusers will needto set Tomcat up as a service. Both approaches are outlined in this section. Automatic Startup on Linux If you’ve installedTomcat via an RPM package, getting it to run on a reboot is just a matter of telling your system to run the tomcat or tomcat55 service (depending on which RPM package you installed) when it enters a multiuser run level. If you know how to use chkconfig, as the root user you can simply chkconfig tomcat on for the run level(s) of your choice. Use the chkconfig commandto make the tomcat service start in the run level(s) of your choice. Here’s an example of how to make it start in run levels 2, 3, 4, and 5: # chkconfig --level 2345 tomcat on If chkconfig does not see the tomcat service, try tomcat55 instead(the JPackage.org RPM package’s init script has this name). Otherwise, you probably did not install Tomcat as an RPM package. Below, we show how to add a simple init script to make it work anyway. 30 | Chapter 1: Getting Started with Tomcat Now, query your configuration to make sure that startup is actually set: # chkconfig --list tomcat tomcat 0:off 1:off 2:on 3:on 4:on 5:on 6:off Now, reboot and see if Tomcat starts up when the system comes back up. If you didn’t use the RPM package to install Tomcat, you can still set up Tomcat to start on reboots. Tomcat does not come with a Linux init script, but it is simple to create one that wouldjust start Tomcat at boot time andstop it on shutdown.- Example 1-2 is a very simple Tomcat init script for Linux. Save this script in a file named tomcat andchange the file ownership andgroup to root, and then chmod it to 755: # chown root.root tomcat # chmod 755 tomcat Copy the script to the /etc/rc.d/init.d directory after modifying the JAVA_HOME and CATALINA_HOME environment variables to fit your system. Then, set the new tomcat service to start andstop automatically by using chkconfig, as shown earlier in this section. Automatic Startup on Solaris If you have installedTomcat via a Blastwave Solaris CSW package, your Tomcat has been preconfigured to start at boot time. You do not have to do anything extra to make it work. If not, you’ll needto create yourself a simple init script, as shown for Linux in the previous section; it shouldwork fine. Save it to /etc/init.d/tomcat andset the permis- sions like this: # chmod 755 /etc/init.d/tomcat # chown root /etc/init.d/tomcat # chgrp sys /etc/init.d/tomcat Set the new tomcat service to start andstop automatically by symbolically linking it into the /etc/rc3.d directory (as the root user): Example 1-2. A Tomcat init script for Linux #!/bin/sh # Tomcat init script for Linux. # # chkconfig: 2345 96 14 # description: The Apache Tomcat servlet/JSP container. JAVA_HOME=/usr/java/jdk1.6.0_02 CATALINA_HOME=/opt/apache-tomcat-6.0.14 export JAVA_HOME CATALINA_HOME exec $CATALINA_HOME/bin/catalina.sh $* Automatic Startup | 31 # ln -s /etc/init.d/tomcat /etc/rc3.d/S63tomcat # ln -s /etc/init.d/tomcat /etc/rc3.d/K37tomcat The numbers S63 and K37 may be variedaccordingto what other startup scripts you have; the S number controls the startup sequence andthe K number controls the shutdown (kill) sequence. The system startup program init invokes all files matching /etc/rc3.d/S* with the parameter start as part of normal system startup, andstart is just the right parameter for catalina.sh. The init program also invokes each script file named rc3.d/K* with the parameter stop when the system is being shut down. Automatic Startup on Windows Under Windows, Tomcat can be run as a Windows service. Although you can use this to start andstop the server, the most common reason for creating a Tomcat ser- vice is to ensure that it is started each time your machine boots up. Your first task is to find the Services control panel. On a standard Windows install, this requires accessing several menus: Start Menu ➝ Programs ➝ Administrative Tools ➝ Services. Alternately, you can go Start Menu ➝ Settings ➝ Control Panel, and then double-click on Administrative Tools, and again on Services. Once you have the Services control panel, locate the entry for Apache Tomcat (the entries are normally in alphabetical order), and double-click on it, as shown in Figure 1-7. Figure 1-7. Automatic startup under Windows 32 | Chapter 1: Getting Started with Tomcat In the Apache Tomcat Properties dialog box, you should ensure that the startup type is set to Automatic rather than Manual, which will cause Tomcat to start up when- ever your machine reboots. Automatic Startup on Mac OS X Mac OS X, like most other operating systems, uses system init scripts to allow you to start, stop, andrestart services automatically just as you wouldon a Linux system via /etc/rc.d/init.d or via BSD’s /etc/init.d. In Mac OS X Tiger (10.4), Apple has intro- duced a new central system-wide controller called launchd.* launchd gives you more flexibility over how services are controlledandwho can access these services. It pro- vides a very simple property list (plist) configuration file that allows you to set up what daemon runs and how the daemon is accessed. Due to the differences† in behavior between how launchd expects the daemon it has launched to react and how the Tomcat scripts operate, we have to create a shell script that won’t fork or have the parent process exit to overcome this problem. Let’s create the script for usage in the tomcat.plist andput it in the Tomcat installa- tion binary directory (both the following shell script and the .plist file are included in the book’s examples; you may download them from http://www.oreilly.com/catalog/ 9780596101060): $ vi /usr/local/tomcat/bin/tomcat-launchd.sh #!/bin/bash # Shell script to launch a process that doesn't quit after launching the JVM # This is required to interact with launchd correctly. function shutdown( ) { $CATALINA_HOME/bin/catalina.sh stop } export CATALINA_HOME=/usr/local/tomcat export TOMCAT_JVM_PID=/tmp/$$ . $CATALINA_HOME/bin/catalina.sh start # Wait here until we receive a signal that tells Tomcat to stop.. trap shutdown HUP INT QUIT ABRT KILL ALRM TERM TSTP wait `cat $TOMCAT_JVM_PID` Next, we needto create the launchd property list file for Tomcat. Loadup your favor- ite text editor and edit tomcat.plist: * You can finda detailedoverviewon Apple’s support page relatedto this great new service: http://developer. apple.com/macosx/launchd.html. † launchd expects the service to be startedandrun until signaled,whereas the scripts for Tomcat ( catalina. sh) launch the Tomcat JVM and then quit. This is a mismatch that the tomcat-launchd.sh script fixes. Automatic Startup | 33 $ vi tomcat.plist Disabled EnvironmentVariables CATALINA_HOME/usr/local/tomcat JAVA_HOME/System/Library/Frameworks/JavaVM. framework/Home Labelorg.apache.tomcat OnDemand ProgramArguments /usr/local/tomcat/bin/tomcat-launchd.sh RunAtLoad ServiceDescriptionApache Tomcat StandardErrorPathusr/local/tomcat/logs/launchd.stderr StandardOutPathusr/local/tomcat/logs/launchd.stdout UserNamenobody Now that we have the configuration file, we needto place it in the correct location so launchd can access it. To ensure the script is executedeven if no users are loggedin, the script should be placed in /Library/LaunchDaemons: $ sudo cp tomcat.plist /Library/LaunchDaemons Another requirement of launchd is that both the daemon and property list file need to be ownedby the root user and the daemon needs to be executable. Let’s ensure that the correct ownership and executable flag is set on these files: $ chown root:wheel tomcat-launchd.sh $ chmod +x tomcat-launchd.sh $ chown root:wheel /Library/LaunchDaemons/tomcat.plist Our final step in this process is to load the script into launchd: $ sudo launchctl load /Library/LaunchDaemons/tomcat.plist You can ensure your plist has been loaded by running the following command: $ sudo launchctl list com.apple.dashboard.advisory.fetch com.apple.dnbobserverd com.apple.KernelEventAgent com.apple.mDNSResponder com.apple.nibindd 34 | Chapter 1: Getting Started with Tomcat com.apple.periodic-daily com.apple.periodic-monthly com.apple.periodic-weekly com.apple.portmap com.apple.syslogd com.vix.cron org.samba.nmbd org.postfix.master org.xinetd.xinetd org.samba.smbd org.apache.tomcat Notice that Tomcat is now running via launchd (org.apache.tomcat) this is the Label you specified in the property list file above. If for some reason it hasn’t loaded, ensure that all your paths are correct, the files have the correct permissions and are otherwise accessible. Automatic Startup on FreeBSD If you installedthe FreeBSD port of Tomcat 6, this section shows the standardway of configuring Tomcat to start at boot time and stop on a shutdown. To enable Tomcat to start on a reboot andbe shut downgracefully as part of the shutdown sequence, you need to put a controller script in the /usr/local/etc/rc.d/ directory. The controller script’s filename must end in .sh, andit must be execut- able (see “man rc”). The FreeBSD port of Tomcat 6 comes with an RCng script that you can use for start- ing, stopping, and restarting the server. This script is /usr/local/etc/rc.d/tomcat60.sh. Make sure you have added this line to your /etc/rc.conf file: tomcat60_enable="YES" This is what enables Tomcat 6 to start at boot time. Once you have done that and you reboot, Tomcat shouldstart. It shouldalso be able to shut downgracefully when you shut down your computer. Testing Your Tomcat Installation Once you have Tomcat installedandstarted,you shouldconfirm that it has success- fully startedup. Open the URL http://localhost:8080 (it’s port 8180 if you’re running FreeBSD andinstalledthe FreeBSD port) in a browser to verify that you see output like that shown in Figure 1-8. Where Did Tomcat Come From? | 35 If you have changedthe port number in server.xml, you will needto use that same port here. Now that Tomcat is up andrunning, you can begin to customize its behavior, which is discussed in Chapter 2. Where Did Tomcat Come From? The first Java servlet container was Sun Microsystems’s Java Web Server (JWS). Sun’s Java Web Server was a product that Sun offered for sale. It was more affordable than most commercial server offerings, but it did not enjoy widespread commercial suc- cess—largely due to Java still being new, and servlets being only recently introduced. One of Java Web Server’s main outgrowths, however, was the Java Servlet Specifica- tion as a de facto standard that Sun documented and made available separately. One big success of JWS was that it put Java servlets in the limelight. Figure 1-8. Success! 36 | Chapter 1: Getting Started with Tomcat In 1996, a plethora of free Java servlet containers became popular. Apache’s JServ and CERN/W3C’s Jigsaw were two of the earliest open source Java servlet containers. They were quickly followedby several more, includingJetty ( http://jetty.mortbay.org), the Locomotive Application Server (see the web archives at http://web.archive.org/web/ */http://www.locomotive.org), Enhydra (http://www.enhydra.org), andmany others. At the same time, commercial servlet containers were starting to become available as the industry embraced the Java Servlet standard; some of these were WebLogic’s Tengah, ATG’s Dynamo, and LiveSoftware’s JRun. In 1997, Sun releasedits first version of the Java Servlet Development Kit (JSDK). The JSDK was a very small servlet container that supportedJSP andhada built-in HTTP 1. 0 web server. In an effort to provide a reference implementation for developing serv- lets, Sun made it available as a free download to anyone wanting to experiment with the new Java server-side standard. It also had success as a testing and development platform in preparation for deployment to a commercial server. In the first half of 1998, Sun announcedits new JSP specification, which built upon the Java Servlet API and allowed more rapid development of dynamic web applica- tion content. After the 2.1 release of the JSDK (now calledthe JSWDK to add“Web” to the name), James Duncan Davidson at Sun rewrote the core of the older JSDK server. At the heart of this new Java servlet engine reference implementation was a brandnew servlet container namedTomcat, andits version number startedat 3.0 because it was a follow-on to version 2.1 that it replaced. Why the Name Tomcat? Tomcat was createdwhen James Duncan Davidson(then an employee at Sun) wrote a new server based on the Servlet and JSP idea but without using any code from JWS. As James put it when we askedhim about this, “O’Reilly books have animals on the covers. So what animal wouldI want on the cover of the O’Reilly book covering the technology? “Furthermore, I wantedthe animal to be something that was self-sufficient. Able to take care of itself, even if neglected, etc. Tomcat came out of that thought.” He code-named it Tomcat, and the name was effectively obscured from view because it was the internal engine of the JSWDK, andnot a productname. Until “. . . at the 4th JavaOne, somebody asked about it in the audience as they had decompiled the sources and wanted to know what com.sun.tomcat was.” Where Did Tomcat Come From? | 37 As the servlet andJSP specifications’ reference implementation, Tomcat evolvedrap- idly. As the specifications became rich with features, so did Tomcat and with it the JSWDK. For various reasons, James andSun wantedto open the codeto the JSWDK. This was largely so developers everywhere could examine how servlets and JSPs operated. Here’s what Jason Hunter of the Apache Software Foundation says about what happened next: Sun wantedto spreadthe adoptionof the technology, especially JSP, andApache was a goodvenue to enable that. From what James saidat the time andsince, they wouldn’t have open sourced it on their own except if Apache (with majority web server marketshare) wouldtake the code,well then! What’s funny is Sun gave it for JSP, Apache took it for servlets. Nevertheless, the open source Tomcat project has enjoyedrapiddevelopmentin areas including both servlets and JSP functionality from the developer community since its donation to the Apache Software Foundation. Being freely distributable, backed by both Sun and the Apache Software Foundation, being the reference implementation for the Java Servlet Specification, andbeing all- around“cool,” Tomcat went on to redefinethe very meaning of a Java server, let alone a servlet container. Today, Tomcat is one of the most widely used open source soft- ware packages and is a collaborative project bustling with activity every day of the year. While Tomcat’s popularity steadily increased, Sun Microsystems moved on to develop a new reference implementation—this time for all of Java EE. The Glassfish Java EE server is the new reference implementation, andthe web container compo- nent of Glassfish is basedheavily on Tomcat. Meanwhile, Tomcat remains the most popular, most widely used open source servlet container implementation. All open source Java EE application server implementations include Tomcat, in whole or in part. Tomcat remains 100 percent compliant with Sun’s latest specifications for serv- lets, JSP, and other Java EE web container specifications. 38 Chapter 2CHAPTER 2 Configuring Tomcat 2 Once Tomcat is up andrunning, you will want to keep an eye on it, to help it along occasionally. Troubleshooting application servers can be intimidating. In this chapter, we show you the various places to look for information about your server, how to find out why things aren’t working, andgive you some examples of common mistakes in setting up andconfiguring Tomcat. Want to run Tomcat on the defaultHTTP port 80? We show you some ways of doing that. You will also find some pointers on what JVM startup switch settings you can use. You’ll learn how you can manage the web user accounts that Tomcat knows about andhow to configure security realms to customize which users can access your Tomcat’s web content. We also show you how to config- ure your Tomcat to open a pool of connections to your database for your webapp to use. Next, we show how to configure Tomcat to use Common Gateway Interface (CGI) programs. Finally, we discuss the Tomcat administration web application, a tool for helping you with the task of keeping Tomcat running. A Word About Using the Apache Web Server You can use Tomcat as a standalone combination web server and servlet container, or you can use it as an add-on servlet container for a separate web server. Both are common, and each is appropriate in certain situations. The Tomcat authors have spent quite a bit of time andeffort to make Tomcat run efficiently as a standalone web server; as a result, it is easy to set up and run a web site without worrying about the issues involvedwith connecting Tomcat to a third- party web server. Tomcat’s built-in web server is a highly efficient HTTP 1.1 server that is quite fast at serving static content once configuredcorrectly for the computer on which it runs. They’ve also added features to Tomcat that one would expect from full-featured web servers, such as CGI scripting, a home directory mapper, and more. Relocating the Web Applications Directory | 39 The Tomcat authors also realizedthat many companies andother organizations already run the Apache httpd web server andmay not want to switch from that server to Tomcat’s built-in web server. The Apache Web Server is the most popular web server on the Internet according to many web surveys* andis arguably the most flexi- ble, fully featured, and supported web server ever written. Even if users running Apache httpd wanted to switch web servers, it may be difficult for them to do so because their web sites are often already too integrated with Apache’s features. Keep in mind, however, that Apache httpd may not be more efficient at serving your content than Tomcat standalone is. Tomcat’s web server is highly optimized, and today’s Java runtimes are very good at natively compiling Tomcat so that the result- ing binary it is running is also highly optimizedfor your operating system andarchi- tecture. Configuring Tomcat so that all of its requests must first travel through Apache httpd may actually slow down Tomcat’s response times, and it is usually the performance of the dynamic content that web server administrators need to improve. With these issues in mind, if you’re still considering using Apache httpd andTomcat together, you will want to refer to Chapter 5 for an in-depth look at how to hook together these two programs. Relocating the Web Applications Directory Depending on how you install and use Tomcat, you may not want to store your web application’s files in the Tomcat distribution’s directory tree. For example, if you plan to upgrade your installation of Tomcat periodically, you probably shouldn’t modify Tomcat’s files—for instance, CATALINA_HOME/conf/server.xml, which you will likely need or want to modify in order to configure Tomcat for your site†— because when you install a newer version of Tomcat’s files into the Tomcat installa- tion directory tree, you may overwrite the server.xml andany other configuration files that you modified for your site. This is the case whether you use an operating- system-specific package of Tomcat (an RPM package, etc.) or an operating-system- neutral archive of Tomcat (.zip or .tar.gz). Upgrading the Tomcat package means that the native package manager may replace your configuration files with stock ver- sions from any new version of the same package that you upgrade to. Usually, pack- age managers save the file they’re replacing if it is a known configuration file, but even then it’s a pain to know what you needto doto get your site back in running order. Regardless of how you installed Tomcat, though, it may be a good idea to keep your web site’s files cleanly separate from the Tomcat distribution files. * Keep in mind, though, that if the survey is counting the number of servers that identify themselves as “Apache” on the beginning of their server identification header string Tomcat identifies itself as “Apache Coyote,” which wouldcount as an “Apache.” No surveys seem to try to count Tomcat installations sepa- rately from Apache httpd installations, so Tomcat’s success makes httpd look better, which in turn makes people want to install and use httpd more. † See Chapter 7 for detailed information about configuring the XML elements in the server.xml file. 40 | Chapter 2: Configuring Tomcat Another scenario in which you may not want to store your web application files in the Tomcat distribution’s directory tree is if you install one copy of the Tomcat dis- tribution, but you wish to run more than one instance of Tomcat on your server computer. There are plenty of reasons why you may want to run more than one Tomcat instance, such as having each one serve different content on different TCP ports andyou want each webapp in its own JVM so they can be operatedindepen- dently. In this case, you don’t want files from one instance clashing with files from another instance. To have one Tomcat distribution installed and run two or more Tomcat JVM instances that are configureddifferently,you must keep each JVM instance’s files separate. During normal usage of Tomcat, the server reads configuration from the conf and webapps directories and writes files to the logs, temp, and work directories. Also, some jar files and class files may needto be loadedfromthe shared, server, and common directory trees. This means that for multiple instances to work, each Tom- cat instance has to have its own set of these directories; they cannot be shared by two differently configured Tomcat JVM instances. The trick to making this work is that you must set the CATALINA_HOME environment variable to where you installedthe Tomcat binary distribution(these files come from http://tomcat.apache.org), andyou must set the CATALINA_BASE environment variable to a different path where you are storing a JVM instance’s files (these files come from you). When you have both of these environment variables set andyou start Tomcat, it will run using your files in CATALINA_BASE, on top of the Tomcat binary distribu- tion in CATALINA_HOME. This is built-in feature of Tomcat allows you to keep Tom- cat’s files separate from your files, but still makes it possible to modify everything you need to modify to configure everything the way you need it to be. First, change directory to the directory you’d like to put an instance’s files within. This will be your CATALINA_BASE directory. It can be anywhere on your system, but we suggest you locate this directory somewhere convenient where you can put a large amount of data: # cd /opt # mkdir tomcat-instance # cd tomcat-instance Next, create a directory for the new Tomcat instance (it should probably be named after the site that will be stored within it): # mkdir groovywigs.com # cd groovywigs.com If you don’t like the dot in the filename, you can change it to a dash or an underscore or make a directory called com and add subdirectories namedafter the domain,such as groovywigs. You’ll endup with a structure like most Java environments: com/groovywigs, com/moocows, org/bigcats, and so forth. Relocating the Web Applications Directory | 41 Now, copy the Tomcat distribution’s config directory to this new directory, and then create all of the other Tomcat instance directories: # cp -a $CATALINA_HOME/conf . # mkdir common logs temp server shared webapps work Make sure that you create these directories and files such that the user you run Tomcat as has read/write permissions to all of these directo- ries and files. Finally, place the web application content for this instance in the webapps subdirec- tory of CATALINA_BASE, just as you wouldin any other configuration of Tomcat. Edit the conf/server.xml file to be specific to this instance. Only modify what you have to in this file to get your instance running the way you needit to. Also, make sure that this Tomcat instance doesn’t try to open the same host and ports as someone else’s Tomcat instance on the same server computer andthat it doesn’ttry to loadthe example webapps that come with Tomcat because these webapps are not foundin your CATALINA_BASE tree. Change the shutdown port to a different port number for each Tomcat instance: and the ports of any connectors: You coulddoa text search for port= andchange the port value of that attribute if its element is not commented out. Remove all of the example Context elements (because you didn’t copy them to your instance’s webapps directory)andanything nestedwithin them, andaddacontext for your own webapp (see Chapter 7 for more information about how to configure a Context). Repeat these steps to create additional CATALINA_BASE instance directories as neces- sary. If you have only one web site, or you want to run only one Tomcat JVM, you need only one CATALINA_BASE tree. To start up an instance, set CATALINA_BASE to the full path of the instance directory, set CATALINA_HOME to the full path of the Tomcat distribution directory, and then start Tomcat normally: # set CATALINA_BASE="/opt/tomcat-instance/groovywigs.com" # set CATALINA_HOME="/opt/tomcat" # export CATALINA_BASE CATALINA_HOME # service tomcat start # Standard way to start on Linux 42 | Chapter 2: Configuring Tomcat You can stop these instances similarly: # set CATALINA_BASE="/opt/tomcat-instance/groovywigs.com" # set CATALINA_HOME="/opt/tomcat" # export CATALINA_BASE CATALINA_HOME # service tomcat stop # Standard way to stop on Linux You may also create small convenience start and stop scripts so that you can start and stop instances easily. Perform the following steps: # cd /opt/tomcat-instance/groovywigs.com # mkdir bin # cd bin Now, edit a file named start and put the following contents in it: #!/bin/sh set CATALINA_BASE="/opt/tomcat-instance/groovywigs.com" set CATALINA_HOME="/opt/tomcat" export CATALINA_BASE CATALINA_HOME service tomcat start # Standard way to start on Linux Make sure to make this script executable: # chmod 700 start Again, make sure that the Tomcat process owner has at least readandexecute per- missions to the bin directory and the new start script. Then, to start up an instance, you can simply use this script: # /opt/tomcat-instance/groovywigs.com/bin/start You can follow the same steps to create a stop script. Once you organize your own files separately from the Tomcat distribution, upgrad- ing Tomcat is easy because you can replace your entire Tomcat distribution direc- tory with a new one without worrying about disturbing any of your own files. The only exception to this wouldbe if you upgradeto a new Tomcat that is not compati- ble with your last Tomcat’s instance files (something that happens once in a while but may be remedied by reading “Migrating from Older Versions of Tomcat” in Chapter 7). Once you start up a web application on a new Tomcat version, be sure to check the logfiles first for any problems. Changing the Port Number from 8080 Tomcat, in a default installation, is configured to listen on port 8080 rather than the conventional web server port number 80. This is sensible because the default port 80 is often in use already and because opening a network server socket listener on the default port 80 requires special privileges on Linux, Solaris, BSD, and other non- Windows operating systems. However, the majority of the time it still makes sense to run Tomcat on port 80 instead of the default 8080. Changing the Port Number from 8080 | 43 To change the port number, edit the main Connector element in the server.xml file. Find the XML tag that looks something like this: Just change the port attribute from 8080 to 80, andrestart Tomcat. Unless that port number is already in use or you lack administrative permission to start a server on port 80, Tomcat should now be operational on port 80. Running a server on port 80 normally requires that it run with high administrative permissions, such as the root account on Linux, Solaris, BSD, andother non- Windows operating systems. You (or your site security policies) may not want to trust Tomcat running as root, but we have not heardeven a single reportedincidentwhere a machine’s security was com- promisedbecause Tomcat was running as root. If you’re worriedabout this, there are other ways of making Tomcat answer on port 80 without running Tomcat’s JVM pro- cess as root. The following sections explain a few ways of doing just that. Relaying Port 80 TCP Connections to Port 8080 It is true that the JVM process must run as the root user in order to open a server socket on port 80 on non-Windows operating systems. But, the JVM would not need to run as root if something outside the JVM process could relay all port 80 TCP con- nections to Tomcat on some port higher than 1024 (such as port 8080, for exam- ple). Tomcat can open its web server on port 8080, andsomething else with the proper permissions can relay port 80 TCP connections to Tomcat’s port 8080. This is often referredto as port relaying or net filtering andis such a handyandcommon feature that there are more ways than one to do this on any given operating system. On Linux, there is a built-in feature called iptables that allows all kinds of firewall- ing, network filtering, andrelaying, andit can easily relay port 80 TCP connections to Tomcat. The iptables feature is a Linux kernel feature that is usually enabledby default and configurable by using the iptables command-line tool. Try running this command as root to see if it is enabled in your Linux kernel: # iptables -t nat -L Chain PREROUTING (policy ACCEPT) target prot opt source destination Chain POSTROUTING (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination 44 | Chapter 2: Configuring Tomcat If you get the same or similar output, you can probably use iptables to relay connec- tions for Tomcat. If instead you get a message like this: iptables v1.3.5: can't initialize iptables table `filter': iptables who? (do you need to insmod?) Perhaps iptables or your kernel needs to be upgraded. it means it is not enabledin your kernel, andyou needto first enable it in your ker- nel before it can work (describing how to do this is beyond the scope of this book). Assuming it works, you can route all port 80 TCP connections to all network desti- nations that the machine is configured for by entering these two commands: # iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8080 # iptables -t nat -I OUTPUT -p tcp --dport 80 -j REDIRECT --to-ports 8080 They will add the necessary relaying rules to your iptables configuration. This tells the kernel that all TCP connections destined for the machine on port 80 need to be redirected to port 8080. If you want to only relay connections for one IP address that your machine is config- ured for, you could instead optionally add a destination IP address by using the --dst switch, like this: # iptables -t nat -I PREROUTING -p tcp --dst 192.168.1.100 --dport 80 -j REDIRECT -- to-ports 8080 # iptables -t nat -I OUTPUT -p tcp --dst 192.168.1.100 --dport 80 -j REDIRECT --to- ports 8080 Just change the 192.168.1.100 IP address above to the IP address on your server that you want to relay connections for. Once you have added your relaying rules, you may list them like this: # iptables -t nat -L Chain PREROUTING (policy ACCEPT) target prot opt source destination REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080 Chain POSTROUTING (policy ACCEPT) target prot opt source destination Chain OUTPUT (policy ACCEPT) target prot opt source destination REDIRECT tcp -- anywhere anywhere tcp dpt:http redir ports 8080 At this point, you shouldbe able to make a request on port 80 andyour Tomcat should get it. Changing the Port Number from 8080 | 45 One drawback of the redirection method is that Tomcat will rewrite the URL to display the actual port. Suppose your site is www.example. com. If a user types http://www.example.com/ into his browser loca- tion field, depending on the web application’s content, Tomcat may rewrite it, andthe user will see http://www.example.com:8080/index. html in his browser location field. Your Tomcat assumes the request came in on port 8080 because it openedits web server connector on port 8080, so whenever it sends a redirect, it will append the port number 8080, unless you add proxyPort="80" to your Connector configuration in server.xml like this: You may also want to set proxyName="hostname.example.com" if your Tomcat installa- tion is serving pages for just one hostname. See the Linux iptables manual page for more information about how iptables works andother options you can use. At least on Linux, this is the easiest way to get Tom- cat answering on port 80 without running it as root. On other operating systems, there are ways of relaying or remapping TCP traffic to different ports. For example, on FreeBSD Unix this is part of the pf (packet filter) mechanism. On FreeBSD, you wouldtypically use a line such as the following in your /etc/pf.conf file: # map tomcat on 8080 to appear to be on 80 rdr on ne3 proto tcp from any to any port 80 -> 127.0.0.1 port 8080 Here, ne3 is the name of your Ethernet interface. The rdr line tells pf to redirect any incoming packets on port 80 to port 8080 instead, where Tomcat will see them. See the pfctl manual page for more details and options. Although we’ve usedport 80 in these examples, you can use the same techniques to make Tomcat listen (or appear to be listening) on any port number from 1 to 65535 that isn’t already in use and on which you have permission to start servers. Running Tomcat on Port 80 via a Service Wrapper Another way to run Tomcat on port 80 as a user other than root is use a service wrapper binary. A service wrapper is a program written in C that is meant just for this purpose: to run a Java server boundto a privilegedport on a non-Windows operating system as a user other than root. The idea is that you start the service wrapper binary as the root user, it instantiates a Java VM with Tomcat in it as a 46 | Chapter 2: Configuring Tomcat separate process that has the root-like capability of opening server sockets on privi- legedports—while running as a non-root user—andTomcat opens its server socket(s) on the privilegedport(s). Then, Tomcat is no longer running as root but is serving requests over the privilegedport. jsvc (short for “Java Service”) is a native ser- vice wrapper that comes with Tomcat’s binary distribution. The jsvc code that comes with Tomcat is a copied portion of the Jakarta Commons Daemon project (http://jakarta.apache.org/ commons/daemon). Each version of Tomcat was built against a partic- ular version of Commons Daemon at the time of its release, so only the version of jsvc that is bundled with Tomcat’s binary distribution is meant to be used with that version of Tomcat. Here’s how to get jsvc working: Unpack your Tomcat’s binary distribution, and there will be a file in the bin/ directory named jsvc.tar.gz. Inside that archive is the source code for the version of jsvc that works with your version of Tomcat. Unpack the archive preferably not near your pro- duction installation of Tomcat. A developer machine is really the right place for this for security reasons, but because you’ll needthese files only temporarily, you can put them wherever you like and delete them once you have jsvc installed and working. Unpack the source where you want to build it: # cd /home/jasonb # gunzip apache-tomcat-6.0.14.tar.gz # tar xvf apache-tomcat-6.0.14.tar # cd apache-tomcat-6.0.14/bin # gunzip jsvc.tar.gz # tar xvf jsvc.tar.gz Change directory into the jsvc-src/ directory: # cd jsvc-src Readthe INSTALL.txt document for the latest information about building the Com- mons Daemon jsvc binary: # more INSTALL.txt As of this writing, here’s how to build it: # ./configure –with-java=$JAVA_HOME Make sure JAVA_HOME is set to the absolute path of your Java installation (either JDK or JRE should work). Then, run make: # make When it is done building, it creates a jsvc executable file in the current directory. Changing the Port Number from 8080 | 47 Now, try running the jsvc commandwith the -help switch. It shouldoutput the usage syntax, like this: # ./jsvc -help Usage: jsvc [-options] class [args...] Where options include: -jvm use a specific Java Virtual Machine. Available JVMs: 'server' -cp / -classpath set search path for service classes and resources -home set the path of your JDK or JRE installation (or set the JAVA_HOME environment variable) -version show the current Java environment version (to check correctness of -home and -jvm. Implies -nodetach) -help / -? show this help page (implies -nodetach) -nodetach don't detach from parent process and become a daemon -debug verbosely print debugging information -check only check service (implies -nodetach) -user user used to run the daemon (defaults to current user) -verbose[:class|gc|jni] enable verbose output -outfile Location for output from stdout (defaults to /dev/null) Use the value '&2' to simulate '1>&2' -errfile Location for output from stderr (defaults to /dev/null) Use the value '&1' to simulate '2>&1' -pidfile Location for output from the file containing the pid of jsvc (defaults to /var/run/jsvc.pid) -D= set a Java system property -X