简体   繁体   中英

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-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.

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.

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.
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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM