从一个Docker容器连接到另一个 [英] Connect from one Docker container to the other one
问题描述
我正在Docker容器中运行Java应用程序,该容器应该将MySQL连接到另一个容器中。尝试使用表格中建议的多个选项,但实际上没有任何效果。这是我的Docker Compose文件:
I am running a Java app inside a Docker container which is supposed to connect MySQL inside the other container. Trying multiple options suggested in the forms, nothing really works. Here is my Docker Compose file:
version: "3"
services:
app:
build:
context: ./
dockerfile: /src/main/docker/Dockerfile
image: app1
environment:
- DB_HOST=Imrans-MacBook-Pro.local
- DB_PORT=3306
ports:
- 8080:8080
networks:
- backend
depends_on:
- mysql
mysql:
image: mysql:5.7.20
hostname: mysql
environment:
- MYSQL_USER=root
- MYSQL_ALLOW_EMPTY_PASSWORD=yes
- MYSQL_DATABASE=app1
ports:
- 3306:3306
command: mysqld --lower_case_table_names=1 --skip-ssl --character_set_server=utf8 --explicit_defaults_for_timestamp
networks:
- backend
networks:
backend:
driver: bridge
其中 DB_HOST = Imrans-MacBook-Pro.local
是我的笔记本电脑的名称。这没有用。有人建议可以使用容器名称,因此可以尝试 DB_HOST = mysql
,但从未成功。
Where DB_HOST=Imrans-MacBook-Pro.local
is my laptop's name. This did not work. Some suggest that the container name can be used so tried DB_HOST= mysql
, never worked.
唯一有效的方法我不时通过笔记本电脑的IP地址,这不是我想要的。因此,在这些容器之间创建通信的一种好方法是什么?
The only thing works from times to time when I pass the laptop's IP address, which is not I want to do. So, what is a good way to create communication between those containers?
推荐答案
我过去曾经使它起作用无需在Docker Compose中显式设置主机网络部分。因为Docker Docker Compose文件中的图像相互放置在Docker网络中,所以您真的不需要做任何事情就可以使它起作用:默认情况下,您应该能够将其附加到Spring应用程序的容器中,并能够 ping mysql
并具有可以解决。
I have, in the past, gotten this to work without explicitly setting the host networking part in Docker Compose. Because Docker images inside a Docker Compose File are put into a Docker Network with each other, you really shouldn't have to do anything to get this to work: by default you should be able to attach into the container for your Spring app and be able to ping mysql
and have it work out.
这篇关于从一个Docker容器连接到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!