I am running MySQL via docker-compose and trying to connect to it from the host, not another container, via a JDBC connection string for an app running on the host and not in a container. The environment is locked down, I cannot create new docker networks or bind a container to 'host' network, bridge is the only option. I can connect to the MySQL instance using the IP address of the container, but this is not much use - I need to use localhost
or 127.0.0.1
. Is this possible? If so, how?
docker-compose.yml
version: '2.2'
services:
db:
container_name: mysql_db
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: 'test-db'
MYSQL_USER: 'test-user'
MYSQL_PASSWORD: 'password'
MYSQL_ROOT_PASSWORD: 'password'
network_mode: bridge
ports:
- '3306:3306'
expose:
- '3306'
volumes:
my-db:
I can connect using the container's IP, like so:
jdbc:mysql://172.17.0.3:3306/test-db
But cannot connect using localhost
, 127.0.0.1
or the container name mysql_db
like so:
jdbc:mysql://localhost:3306/test-db
jdbc:mysql://127.0.0.1:3306/test-db
jdbc:mysql://mysql_db:3306/test-db
Any ideas?
Since 127.0.0.1
and localhost
means the host
your docker
is currently running, so you cannot connect to your host's mysql
.
I also recommend connect container using hostname
:
docker run -it --network bridge --rm mysql mysql -hmysql_db -utest-user –ppassword
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.