使用Docker Compose并尝试将spring引导Web应用程序容器与mysql容器链接时,我收到“java.net.UnkownHostException:mysql:unknown error”。
docker-compose.yml 更新#1
version: '2'
services:
web:
depends_on:
- db
image: thomptr/rest-services-ui:latest
ports:
- "9000:9000"
links:
- "db:database"
restart: always
environment:
SPRING_PROFILES_ACTIVE: dev
envTarget: dev
db:
image: mysql:5.7
ports:
- "3307:3306"
volumes:
- "/home/trevor/softwareDev/mySql/dump:/docker-entrypoint-initdb.d"
environment:
MYSQL_ROOT_PASSWORD: legion03
MYSQL_DATABASE: dev
MYSQL_USER: dbuser
MYSQL_PASSWORD: legion03
application-dev.properties 更新#1
spring.profiles.active=dev
server.contextPath=/restservices
server.port: 9000
spring.datasource.initialize=false
spring.datasource.platform=mysql
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://database:3306/dev
spring.datasource.username=dbuser
spring.datasource.password=legion03;
hibernate.level.logging=debug
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.database=mysql
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
来自/ dockercompose_web_1容器的日志
2016-07-01 04:17:24.119 ERROR 1 --- [ost-startStop-1] o.a.tomcat.jdbc.pool.ConnectionPool : Unable to create initial connections of pool.
com.mysql.jdbc.exceptions.jdbc4.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.
Caused by: java.net.UnknownHostException: mysql: unknown error
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
更新#2 Nguyen Sy Thanh Son提出的方法是正确的。我的解决方案使用public wait-for-it.sh脚本。请在此处查看我的解决方案:https://github.com/thomptr/DockerDemo
答案 0 :(得分:0)
web
容器在mysql
容器启动之前启动时会发生此错误。
要解决此问题,我认为您应该在entrypont.sh
web
图片中添加一个脚本,如下所示
host="db"
password="$MYSQL_ROOT_PASSWORD" #mysql root password
until mysql -h "$host" -uroot -p$password; do
>&2 echo "MYSQL is unavailable - sleeping"
sleep 1
done
>&2 echo "MYSQL is up - executing command"
# start your app here
上面的脚本将等到mysql启动后再运行应用程序
应用程序的Dockerfile应包含:
# run app
COPY entrypoint.sh /
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
答案 1 :(得分:0)
我认为这个错误是由于第一个容器不知道谁是db。 从容器A到容器B的链接不会修改两个容器中的/ etc / hosts。
实现此目的的另一种方法是使用别名。你应该在这里找到你需要的所有信息
https://docs.docker.com/compose/compose-file/#aliases
并修改spring param:
spring.datasource.url=jdbc:mysql://<whatever alias you choose for db>:3306/dev
如果有效,请告诉我。