标签:context ext 数据源 jndi数据源 jdbc isa auth data cti
上一篇完成了通过docker部署nginx+tomcat的基础软件架构,但是距离一个真正可用的软件架构还差得很远。其中最重要的一点是缺少数据库这个角色的存在,那么本篇就来完善这一点。
废话少说,直接进入正题。
首先拉取mysql镜像:
docker pull mysql:5.7
创建本地mysql目录:
mkdir -p ~/mysql/data ~/mysql/conf ~/mysql/logs
chmod -R 777 ~/mysql/logs
在mysql/conf目录下创建配置文件my.cnf:
# For advice on how to change settings please see # http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html [mysqld] # # Remove leading # and set to the amount of RAM for the most important data # cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%. # innodb_buffer_pool_size = 128M # # Remove leading # to turn on a very important data integrity option: logging # changes to the binary log between backups. # log_bin # # Remove leading # to set options mainly useful for reporting servers. # The server defaults are faster for transactions and fast SELECTs. # Adjust sizes as needed, experiment to find the optimal values. # join_buffer_size = 128M # sort_buffer_size = 2M # read_rnd_buffer_size = 2M datadir=/var/lib/mysql socket=/var/lib/mysql/mysql.sock # Disabling symbolic-links is recommended to prevent assorted security risks symbolic-links=0 log-error=/var/log/mysql/error.log pid-file=/var/run/mysqld/mysqld.pid # disabling the password validation #validate_password=off # set bind-address #bind-address=0.0.0.0
启动mysql:
docker run -d -p 3306:3306 --name mysql -e MYSQL_ROOT_PASSWORD=admin -v ~/mysql/conf:/etc/mysql/conf.d -v ~/mysql/data:/var/lib/mysql -v ~/mysql/logs:/var/log/mysql mysql:5.7
登录mysql测试下(root密码已经已经设置成了admin):
mysql -uroot -p -h 172.17.0.2
看上去没什么问题??
创建tomcat的jndi数据源tomcat/conf/context.xml:
<?xml version="1.0" encoding="UTF-8"?> <Context> <Resource name="mysql/test" auth="Container" type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://172.17.0.2:3306/test" username="root" password="admin" maxActive="20" maxIdle="10" maxWait="10000" /> </Context>
新建一个javaweb工程demo,并配置web.xml:
<resource-ref> <res-ref-name>mysql/test</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
创建测试页面testdb.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="javax.sql.*" %> <%@ page import="javax.naming.*" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>connect to mysql/test</title> </head> <body> <% Context context = new InitialContext(); DataSource dataSource = (DataSource) context.lookup("java:comp/env/mysql/test"); Connection conn = dataSource.getConnection(); out.println("Connection.isValid: " + conn.isValid(3)); conn.close(); %> </body> </html>
打包demo工程上传到tomcat/webapps下,重启tomcat测试下:
docker restart tomcat1
docker restart tomcat2
测试下tomcat与mysql的连接是否成功:
ok, it works!
使用docker部署nginx+tomcat架构(2):访问mysql数据库
标签:context ext 数据源 jndi数据源 jdbc isa auth data cti
原文地址:https://www.cnblogs.com/lichmama/p/11380169.html