Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

connecting to a mysql container: what's the equivalent of localhost inside a docker compose project?

I have this docker-compose.yml file, which has one service (log_app) trying to write to a mysql database (mydb).

version: '3.4'
services:
  mydb:
    container_name: mysql_data
    restart: always
    image: mysql:8.0.22
    environment:
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PW}
      MYSQL_DATABASE: ib
      MYSQL_PASSWORD: ${MYSQL_PW}
    volumes:
      - ./init.sql:/docker-entrypoint-initdb.d/init.sql
      - ./mysql-data:/var/lib/mysql
  tws:
    build: .
    container_name: ib_logger_app
    volumes:
      - ./ib/IBController.ini:/root/IBController/IBController.ini
      - ./ib/jts.ini:/root/Jts/jts.ini
    environment:
      TRADING_MODE: ${TWS_TRADING_MODE}
      TWSUSERID: ${TWS_USER_ID}
      TWSPASSWORD: ${TWS_PASSWORD}
      FIXUSERID:
      FIXPASSWORD:
      XVFB_ARGS: -ac -screen 0 1024x768x16 +extension RANDR
    restart: always
    ports:
      - 5901:5900
    depends_on:
      - mydb
  log_app:
    build: log_app/ib_client
    environment:
      - IB_GATEWAY_URLNAME=tws
      - IB_GATEWAY_URLPORT=4004
      - MKT_DATA_TYPE=4
    restart: on-failure
    depends_on:
      - tws
      - mydb
volumes:
  mysql-data:

When I run this on a bare metal server, everything works fine, but in that situation, I connect to localhost on port 3306. This doesn't seem to work here, though. I get

Can't connect to MySQL server on 'localhost' (99)

I've been reading that 3306 is still the right port, but localhost and 127.0.0.1 are wrong now. Neither works for me.

I've also seen some answers on this site that recommend changing localhost to host.docker.internal, but that gives me this:

Can't connect to MySQL server on 'host.docker.internal' (111)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The host name will be the container name as defined in your docker-compose file.

In your example, you should use mydb:3306 instead of localhost:3306

EDIT:

one way to ensure that is to exec into the container that you want to connect from and run:

telnet mydb 3306

and see if it works (but t might require additional installation of telnet).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...