[英]Not able to connect to MySQL with Docker container name but can connect with localhost
I am not able to connect to MySQL using Docker container name in connection string but can connect with localhost. 我无法使用连接字符串中的Docker容器名称连接到MySQL,但可以与localhost连接。
docker-compose: 码头工人组成:
mysql-docker-container:
image: mysql:latest
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=test
- MYSQL_PASSWORD=test
ports:
- 3306:3306
volumes:
- /data/mysql
app:
image: app
build:
context: ./
dockerfile: Dockerfile
depends_on:
- mysql-docker-container
links:
- mysql-docker-container:mysql-docker-container
ports:
- 9090:9090
volumes:
- /data/p2c-app
environment:
- DATABASE_HOST=mysql-docker-container
- DATABASE_USER=testuser
- DATABASE_PASWORD=testuser
- DATABASE_NAME=test
- DATABASE_PORT=3306
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true
Above works, but I want with container name like below - I am getting CONNECTION REFUSED 上面的作品,但我想要像下面的容器名称-我被拒绝连接
spring.datasource.url=jdbc:mysql://mysql-docker-container:3306/test?useSSL=false&allowPublicKeyRetrieval=true
What am I doing wrong? 我究竟做错了什么?
You can update /etc/hosts
if localhost connection works. 如果localhost连接有效,则可以更新
/etc/hosts
。
127.0.0.1 localhost mysql-docker-container
To check whether mysql-docker-container
is reachable from the app container you can open a tty and ping. 要检查是否可以从应用程序容器访问
mysql-docker-container
container,可以打开tty和ping。
docker exec -it app_container_name bash
ping mysql-docker-container
Everything is ok. 一切都好。
It seems the database service is up but the mysql is in the startup process. 似乎数据库服务已启动,但是mysql正在启动过程中。
And the app service starts up then and can not reach to the database. 然后,该应用程序服务将启动,并且无法访问数据库。
There are some workarounds for this situation. 对于这种情况,有一些解决方法。
But the simple one is that you add below to app service. 但简单的一件事是您将以下内容添加到应用程序服务中。
restart: on-failure
And note that depends_on
section just means in docker container context not in underlying services. 请注意,
depends_on
部分仅表示在depends_on
容器上下文中,而不在基础服务中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.