简体   繁体   English

如何:运行 java jar 的 Docker 容器连接到主机 mysql 服务器?

[英]How to: Docker container running java jar connecting to host mysql server?

I wrote a simple java program that should connect to the host machine running a MYSQL server and insert a record.我编写了一个简单的 java 程序,它应该连接到运行 MYSQL 服务器的主机并插入一条记录。 The java progam is running inside a docker container with an ubuntu base image. java 程序在一个 docker 容器内运行,其中包含一个 ubuntu 基础镜像。 At this point I have the jar working but can't connect to the host machine MYSQL server yet.在这一点上,我有 jar 工作,但还不能连接到主机 MYSQL 服务器。

I've tried different mysql server installs and coppied from other dockerfiles in the hope to copy/past something together that works but it's getting messy and I don't know what parts are necessary anymore.我尝试了不同的 mysql 服务器安装并从其他 dockerfiles 复制,希望将一些有效的东西复制/过去,但它变得混乱,我不知道需要哪些部分了。

Java code:爪哇代码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

class ConnectionTest {

    private Connection conn;

    ConnectionTest() throws IOException, ClassNotFoundException {
        try {
            test();
        } catch (SQLException e) {
            logError(e);
        }
    }

    private void logError(SQLException e) throws IOException {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        String sStackTrace = sw.toString();

        File fout = new File("logs.txt");
        FileOutputStream fos = new FileOutputStream(fout);

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));

        bw.write(sStackTrace);

        bw.close();
    }

    private void test() throws SQLException, ClassNotFoundException { ;
        String hostname = "localhost";
        String dbName = "test";
        String userName = "root";
        String password = "";

        Class.forName("com.mysql.cj.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://" + hostname + ":3306/" + dbName + "?useLegacyDatetimeCode=false&serverTimezone=Europe/Paris", userName, password);

        PreparedStatement prep = conn.prepareStatement("INSERT INTO test(Login, Password) values('test', 'test')");
        prep.execute();
    }
}

Dockerfile: Dockerfile:


RUN mkdir -p /root/java
COPY jdk-8u221-linux-x64.tar.gz /
RUN tar -zxf jdk-8u221-linux-x64.tar.gz -C /root/java

RUN apt-get update
RUN update-alternatives --install /usr/bin/java java /root/java/jdk1.8.0_221/bin/java 100

ENV JAVA_HOME /root/java/jdk1.8.0_221/bin
RUN export JAVA_HOME

RUN apt-get update \
 && DEBIAN_FRONTEND=noninteractive apt-get install -y mysql-server \
 && sed -i "s/127.0.0.1/0.0.0.0/g" /etc/mysql/mysql.conf.d/mysqld.cnf \
 && mkdir /var/run/mysqld \
 && chown -R mysql:mysql /var/run/mysqld

VOLUME ["/var/lib/mysql"]

CMD ["mysqld_safe"]

EXPOSE 3306

COPY lib /root/test/lib
COPY entrypoint.sh /

ENTRYPOINT ["/entrypoint.sh"]

Entrypoint.sh:入口点.sh:

chmod -R 777 /root/test

cd /root/test

java -cp "lib/*" -jar lib/DockerTest.jar

tail -f /dev/null

/root/test/lib contains both the mysql-connector-java.jar and the DockerTest.jar. /root/test/lib 包含 mysql-connector-java.jar 和 DockerTest.jar。 If I run mysqld before the jar the server starts but the jar won't launch.如果我在 jar 之前运行 mysqld 服务器启动但 jar 不会启动。

MYSQL status when the server is running:服务器运行时的MYSQL状态:

$ winpty docker exec -it mysql_container service mysql status
 * /usr/bin/mysqladmin  Ver 8.42 Distrib 5.7.27, for Linux on x86_64
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Server version          5.7.27-0ubuntu0.16.04.1
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/run/mysqld/mysqld.sock
Uptime:                 3 sec

Threads: 1  Questions: 4  Slow queries: 0  Opens: 105  Flush tables: 1  Open tables: 98  Queries per second avg: 1.333

Error when running just the jar:仅运行 jar 时出错:

com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
        at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
        at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:832)
        at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:456)
        at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:240)
        at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:207)
        at java.sql.DriverManager.getConnection(DriverManager.java:664)
        at java.sql.DriverManager.getConnection(DriverManager.java:247)
        at ConnectionTest.test(ConnectionTest.java:42)
        at ConnectionTest.<init>(ConnectionTest.java:13)
        at Main.main(Main.java:5)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure

如果你正在使用Spring,你可以设置spring.datasource.urlapplication.properties到使用host.docker.internal:3306如果MySQL是你的本地/主机上运行。

spring.datasource.url=jdbc:mysql://host.docker.internal:3306/<yourdatabase>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Docker容器中的Java服务未连接到主机mysql - Java service in docker container not connecting to host mysql 从 docker 容器连接到主机 mysql db 时连接被拒绝 - Connection refused when connecting to host mysql db from docker container 容器中运行的Java程序内部的Docker主机IP - Docker host IP inside java program running in the container 将 Docker Sqlite 容器连接到 Java - Connecting Docker Sqlite container to Java 将 SQL 开发人员与在 EC2 中的 Docker 容器上运行的 MYSQL 服务器连接 - Connect SQL developer with MYSQL server running on Docker container in EC2 如何使用 docker 容器内我本地机器上运行的 MySQL 服务器用于 DropWizard 应用程序? - How to use the MySQL server running on my local machine inside the docker container for a DropWizard application? 连接到在Docker容器上运行的远程activemq实例 - Connecting to remote activemq instance running on docker container 将运行在bridge网络上的Docker Container连接到Localhost - Connecting Docker Container running on bridge network to Localhost 连接到在 docker 容器中运行的 Kafka 时出错 - Error connecting to Kafka running in docker container 如何使用两个 Java 应用程序和 Mysql 服务器创建 docker 容器? - How do I create a docker container with two Java applications and Mysql server?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM