access denied connecting to mysql from tomcat webapp

October 7th, 2007
If you are getting an AccessControlException when you try to connect to MySQL (or somewhere else) from your web application in a freshly installed Tomcat server, it's probably because Tomcat does not allow your web apps to open socket connections, out of the box.

This is the error message in my case:

com.mysql.jdbc.CommunicationsException:
Communications link failure due to underlying exception:
java.security.AccessControlException: access denied
(java.net.SocketPermission localhost resolve)
...
at java.sql.DriverManager.
getConnection(DriverManager.java:185)


That happens because Tomcat does not allow the application to connect to MySQL. To overcome this you have to explicitly tell Tomcat to allow connection to the MySQL host, in my case the MySQL was in the same host, so I had to add the following lines in my /etc/tomcat5/policy.d/04webapps.policy:

permission java.net.SocketPermission "localhost", "resolve";
permission java.net.SocketPermission "127.0.0.1:3306", "connect";


You may need to change these values to meet your configuration's needs.

It is also possible (though, not recommended) to tell Tomcat to never deny access to your web applications, for any reason. Simply add the following line in your Tomcat's webapps policy file:

permission java.security.AllPermission;

Please note that for your changes to take effect you have to restart Tomcat:

sudo /etc/init.d/tomcat5 restart

The above have been tested and seem to work in Ubuntu 6.06LTS (Dapper Drake) Server.

Leave a Reply