Home  >  Q&A  >  body text

Unable to connect to MySQL docker container from another container under the same network, but accessible from outside

I have two containers - "node.js" and "mysql", both set up to be on the same network. Doing docker-compose up -d starts the containers and they are working, I can access "node.js" and "mysql" respectively from the outside.

But I can't connect to "mysql" from "node.js". Am I doing something wrong here?

version: '3'

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    env_file: .env
    volumes:
      - .:/app
    ports:
      - ${APP_PORT}:${APP_PORT}
    depends_on:
      - mysql
    networks:
      - appnet

  mysql:
    image: mysql:8.0
    restart: always
    env_file: .env
    environment:
      - MYSQL_ROOT_HOST=%
      - MYSQL_ROOT_PASSWORD=${DB_PASSWORD}
      - MYSQL_DATABASE=${DB_NAME}
      - MYSQL_USER=${DB_USERNAME}
      - MYSQL_PASSWORD=${DB_PASSWORD}
    volumes:
      - mysql-data:/var/lib/mysql
    ports:
      - ${DB_PORT}:${DB_PORT}
    networks:
      - appnet

networks:
  appnet:

volumes:
  mysql-data:

To connect to MySQL, I used the "knex.js" package, which works fine on my local machine (same docker configuration)

P粉116631591P粉116631591372 days ago432

reply all(1)I'll reply

  • P粉232793765

    P粉2327937652023-09-13 14:36:34

    Should be seen on an environment level that may be poorly built, here is a link containing docker-compose:

    https://varsubham.medium.com/nodejs-mysql-docker -compose-ad156cd0c885

    Hope this helps you

    reply
    0
  • Cancelreply